Advertisement
thegreen9

UNITY gravity simulation

Apr 7th, 2018
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.32 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class Gravity : MonoBehaviour {
  6.  
  7.         public float Radius;
  8.         public float GravitationalPull; // Pull force
  9.         public float MinRadius; // Minimum distance to pull from
  10.         public float DistanceMultiplier;
  11.  
  12.         public LayerMask LayersToPull;
  13.  
  14.         void FixedUpdate()
  15.         {
  16.             Collider2D[] colliders = Physics2D.OverlapCircleAll(gameObject.transform.position, PullRadius, LayersToPull);
  17.  
  18.             foreach (var collider in colliders)
  19.             {
  20.                 Rigidbody2D rb = collider.GetComponent<Rigidbody2D>();
  21.  
  22.                 if (rb == null) continue;
  23.  
  24.                 Vector2 direction = gameObject.transform.position - collider.transform.position;
  25.  
  26.                
  27.  
  28.                 float distance = direction.sqrMagnitude*DistanceMultiplier + 1; // Учитываем дальность от центра
  29.  
  30.                 // Учитываем массу обьекта
  31.                 rb.velocity /=1.3f;
  32.                 rb.AddForce(direction.normalized * (GravitationalPull / distance) * rb.mass * Time.fixedDeltaTime);
  33.             }
  34.         }
  35.         void OnDrawGizmosSelected()
  36.         {
  37.             Gizmos.color = Color.blue;
  38.             Gizmos.DrawSphere(gameObject.transform.position, PullRadius);
  39.         }
  40.  
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement