我正在做一个简单的n体仿真。现在,我要对其进行“强制执行”,这意味着我要计算每帧每个对象在每个其他对象上施加的所有力。
我现在的问题是,如果我选择大量的对象(例如2000),在某些情况下,刚开始时对象“行星”会消失约2帧。当我通过添加System.out.println(PlanetHandler.planets.get(0).position.x);到主循环中检查发生了什么时,我得到
487.0
486.99454
NaN
NaN
通过注释一些东西和反复试验,我发现问题出在这里:
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);
}
}
}
“行星”列表是CopyOnWriteArray<Planets>。我已经花了很长时间了,但是还没有弄清楚是什么导致值(位置,速度)过大。也许有一定经验的人或者通常精通这种事情的人可以帮助我。
12345678_0001
相关分类