Friday, March 7, 2014

Perfect Gravity Simulation Script

I took a break for a bit to just play around with something I had on my mind. I was wondering how I could do realistic body to body gravity simulation in unity, possibly for future use in a game mechanic. Unity's built in gravity must be set to 0, or it won't work correctly. I threw together a script based on Newton's law of universal gravitation, and came up with the following snippit.

 using UnityEngine;  
 using System.Collections;  
   
 public class GravityForAllObjects : MonoBehaviour  
 {  
   
   private float gravitationalForce;  
   private Rigidbody[] rbs;  
   
      void FixedUpdate ()  
   {  
     rbs = GameObject.FindObjectsOfType<Rigidbody>();  
     foreach (Rigidbody rb1 in rbs)  
     {  
       foreach (Rigidbody rb2 in rbs)  
       {  
         if (rb1 != rb2)  
           ApplyGravity(rb1, rb2);  
       }  
     }  
      }  
   void ApplyGravity(Rigidbody object1, Rigidbody object2)  
   {  
     // Real value for G is 0.0000000000667384 -- using larger value in order to use smaller masses i.e. true mass divided by 1,000,000,000 kg  
     // mass in killograms, distance in meters, yields force in newtons.  
     gravitationalForce = 0.0667384f * ((object1.mass * object2.mass) / (object2.transform.position - object1.transform.position).sqrMagnitude);  
     object1.AddForce((object2.transform.position - object1.transform.position) * gravitationalForce, ForceMode.Force);  
   }  
 }  

I'm not sure how useful this code can be, but I decided to share it anyway. Unlike other gravity scripts I've seen, this one actually takes the mass of both rigidbodies into account, and adds force to both. If you set up a few objects in the editor with a simple script to set an initial velocity perpendicular to the line between the object and a single more massive object, you can easily achieve orbit-like patterns. I'm not sure how well this can scale up/down.

No comments:

Post a Comment