我正在制作一个简单的 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>
。
我已经研究这个问题有一段时间了,但还没有弄清楚是什么导致这些值(位置、速度)变得南。也许有这方面经验或通常擅长此类事情的人可以帮助我。
最佳答案
这是 JVM 为您提供 NAN 的典型情况。您遇到的是零除以零(0/0),这在数学中是一种不确定的形式。
if float dist = Vector2Math.distance(planet.position, otherPlanet.position);
返回 0。
下一条语句
float force = Constants.GRAVITATIONAL_CONSTANT * ((planet.mass*otherPlanet.mass)/(dist*dist));
其中计算力被除以零。
此外,我建议您在需要精度时使用 BigDecimal。也可以引用答案之一here
关于java - 几帧后对象变量变为 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50927892/