Advertisement
Guest User

MultiBody Gravity Calculation (approximate)

a guest
Jul 27th, 2016
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.94 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3.  
  4. public class ChangeGravity : MonoBehaviour {
  5.  
  6.    
  7.     private Transform moonT;
  8.  
  9.     public Transform [] GravitySources;
  10.  
  11.  
  12.     [SerializeField]
  13.     float gravityScale = 10f;
  14.     Rigidbody2D rb;
  15.  
  16.     void Awake()
  17.     {
  18.         rb = GetComponent<Rigidbody2D>();
  19.     }
  20.  
  21.     void FixedUpdate () {
  22.  
  23.         Vector3 totalGravity = Vector3.zero;
  24.  
  25.         for (int i = 0; i < GravitySources.Length; i++)
  26.         {
  27.             Vector3 thisGravity = (GravitySources[i].position - transform.position).normalized * gravityScale * Time.fixedDeltaTime
  28.                                                          / (GravitySources[i].position - transform.position).sqrMagnitude;
  29.  
  30.             rb.AddForce(thisGravity);
  31.  
  32.             totalGravity += thisGravity;
  33.            
  34.          
  35.         }
  36.  
  37.         transform.rotation = Quaternion.LookRotation(Vector3.forward, -totalGravity);
  38.  
  39.     }
  40.  
  41.    
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement