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