I am attempting to make a realistic gravity simulation that can use the mass of an object to then calculate how much gravity it has using Newton’s law of universal gravity. Here is what I have so far:
function gravity(float m1, m2, r)
{
f = 6.674 e -11 * m1 * m2 / (r * r);
return f;
}
Of course this is only a start, and I have no idea what to do from here. Any help is welcome!
Hello !
I had the same issue, and even if the topic is old, it could help someone…
So here’s a code. It’s pretty simple, but it works.
void ApplyGravity(Rigidbody A, Rigidbody B)
{
//This is how to get the distance vector between two objects.
Vector3 dist = B.transform.position - A.transform.position;
float r = dist.magnitude;
dist /= r;
//This is the Newton's equation
//G = 6.67 * 10^-11 N.m².kg^-2
float force = ((float)G * A.mass * B.mass) / (r * r);
//Then, just apply the forces
A.AddForce (dist * force);
B.AddForce (-dist * force);
}
Every “planet” or whatever must have the tag “Object”
void FixedUpdate ()
{
//Get every object
Objects = GameObject.FindGameObjectsWithTag ("Object");
//the gravity between each couple of object is calculated
foreach (GameObject ObjectA in Objects)
{
foreach (GameObject ObjectB in Objects)
{
//Objects must not self interact
if(ObjectA == ObjectB)
continue;
ApplyGravity(ObjectA.rigidbody, ObjectB.rigidbody);
}
}
}
I’m sorry, i’m not into Javascript, this is C#
Hope this will help ! Have a nice day.
Cool - for those of you who need the full class listing - here it is (in a class called GameManager)
-(this also gives a orbit between the two objects)
using UnityEngine;
using System.Collections;
public class GameManager : MonoBehaviour {
// Use this for initialization
void Start () {
GameObject[] Objects = GameObject.FindGameObjectsWithTag ("Planet");
//the gravity between each couple of object is calculated
foreach (GameObject ObjectA in Objects)
{
ObjectA.rigidbody.AddForce(new Vector3(100,0,0));
}
}
void ApplyGravity(Rigidbody A, Rigidbody B)
{
//This is how to get the distance vector between two objects.
Vector3 dist = B.transform.position - A.transform.position;
float r = dist.magnitude;
dist /= r;
//This is the Newton's equation
//G = 6.67 * 10^-11 N.m².kg^-2
double G = 6.674f * (10 ^ 11);
float force = ((float)G * A.mass * B.mass) / (r * r);
//Then, just apply the forces
A.AddForce (dist * force);
B.AddForce (-dist * force);
}
void FixedUpdate ()
{
//Get every object
GameObject[] Objects = GameObject.FindGameObjectsWithTag ("Planet");
//the gravity between each couple of object is calculated
foreach (GameObject ObjectA in Objects)
{
foreach (GameObject ObjectB in Objects)
{
//Objects must not self interact
if(ObjectA == ObjectB)
continue;
ApplyGravity(ObjectA.rigidbody, ObjectB.rigidbody);
}
}
}