I'm currently working on a simple simulator in Unity3D that involves planets orbiting each other. I wrote the following C# script to do that. It uses the classic gravitational formula,
$$F=G\frac{m_1m_2}{r^2}$$
using UnityEngine;
/// <summary>
/// Class used for calculating
/// how an object orbits another
/// object.
/// </summary>
/// <param name="parentObject">The parent gameObject to orbit.</param>
/// <param name="objectMass">The mass of the object.</param>
/// <param name="gravityConstant">The gravitational constant.</param>
[RequireComponent(typeof(Rigidbody))]
public class OrbitObject : MonoBehaviour
{
public OrbitObject parentObject;
public float objectMass;
public float gravityConstant;
private Vector3 parentPosition;
private float parentMass;
/// <summary>
/// Calculates the gravitational attraction.
/// </summary>
/// <returns>The force to apply</returns>
Vector3 CalculateGravitationalForce()
{
this.parentPosition = this.parentObject.transform.position;
Vector3 force = this.parentPosition - transform.position;
float distance = force.magnitude;
float strength = (this.gravityConstant * this.parentMass * this.objectMass) / (distance * distance);
force.Normalize();
force = force * strength;
return force;
}
/// <summary>
/// FixedUpdate is run once per frame.
/// FixedUpdate is used so that calculations
/// don't need to be multiplied by Time.deltaTime.
/// </summary>
void FixedUpdate()
{
rigidbody.AddForce(this.CalculateGravitationalForce());
}
/// <summary>
/// Start this instance.
/// </summary>
void Start()
{
this.parentPosition = this.parentObject.gameObject.transform.position;
this.parentMass = this.parentObject.objectMass;
}
}
For those who are curious, a gif of the script in action can be found here.