I'm making a simple n-Body Simulation. For now, I'm "bruteforcing" it, this means I calculate every force excerted by every object on every other object every frame.
My problem right now is that if I choose a big number of objects, say 2000, in some cases right at the start the objects "planets" dissapear withing about 2 frames. When I check what's happening by adding System.out.println(PlanetHandler.planets.get(0).position.x);
into the main loop, I get
487.0
486.99454
NaN
NaN
By commenting out some stuff and trial-and-error, I found that the problem lies here:
private static void computeAndSetPullForce(Planet planet)
{
for(Planet otherPlanet : planets)
{
//Also here, if we are deleting the planet, don't interact with it.
if(otherPlanet != planet && !otherPlanet.delete)
{
//First we get the x,y and magnitudal distance between the two bodies.
int xDist = (int) (otherPlanet.position.x - planet.position.x);
int yDist = (int) (otherPlanet.position.y - planet.position.y);
float dist = Vector2Math.distance(planet.position, otherPlanet.position);
//Now we compute first the total and then the component forces
//Depending on choice, use r or r^2
float force = Constants.GRAVITATIONAL_CONSTANT * ((planet.mass*otherPlanet.mass)/(dist*dist));
float forceX = force * xDist/dist;
float forceY = force * yDist/dist;
//Given the component forces, we construct the force vector and apply it to the body.
Vector2 forceVec = new Vector2(forceX, forceY);
planet.force = Vector2Math.add(planet.force, forceVec);
}
}
}
The "planets" list is a CopyOnWriteArray<Planets>
.
I've been at this for quite some time now, but haven't figured out what might be causing the values (position, velocity) to go Nan. Maybe someone who's either had some experience with this or is generally adept at this sort of thing could help me out.