Hey guys. For a class project I am attempting the Three Body Problem using unity.
I’ve attempted to get this to work for about 2 days and I cant seem to figure out what’s going wrong.
I either get NaN values or infinity values instead of the planets being attracted together.
Any help would be greatly appreciated.
public class Planet
{
public float mass = 1f;
public Transform r;
}
public class ThreeBodyPlane : MonoBehaviour
{
public const float G = 6.67430f;
[SerializeField] private Planet[] planets = new Planet[3];
[SerializeField] private float size = 1f;
private Vector3[] triangle = new Vector3[3];
float timer = 0;
bool timerReached = false;
void Start()
{
triangle[0].x += -size;
triangle[1].z += size;
triangle[2].x += size;
for (int i = 0; i < 2; i++) {
planets[i].r.position = triangle[i];
}
}
void Update(){
Planet p1 = planets[0];
Planet p2 = planets[1];
Planet p3 = planets[2];
p1.r.position = NewtonianEquation(p1, p2, p3);
p2.r.position = NewtonianEquation(p2, p3, p1);
p3.r.position = NewtonianEquation(p3, p1, p2);
}
Vector3 NewtonianEquation(Planet p1, Planet p2, Planet p3){
return -G * p2.mass * Divide(p1.r.position - p2.r.position, AbsCubedVector3(p1.r.position - p2.r.position)) -
G * p3.mass * Divide(p1.r.position - p3.r.position, AbsCubedVector3(p1.r.position - p3.r.position));
}
Vector3 Divide(Vector3 v1, Vector3 v2)
{
return new Vector3(v2.x / v1.x, v2.y / v1.y, v2.z / v1.z);
}
Vector3 AbsCubedVector3(Vector3 value){
return new Vector3(AbsCubed(value.x), AbsCubed(value.y), AbsCubed(value.z));
}
float AbsCubed(float value){
return Mathf.Pow(Mathf.Abs(value), 3);
}
}
[/ICODE]