为什么物体在第二个循环示例中似乎损坏了,我正在尝试优化我的行星系统以支持更多物体。
for(Body body : bodies){
PVector totalForce = new PVector();
for(Body other : bodies){
if(body != other){
PVector fxy = body.attraction(other);
totalForce.x += fxy.x;
totalForce.y += fxy.y;
}
}
body.vel.x += totalForce.x / body.mass * timestep;
body.vel.y += totalForce.y / body.mass * timestep;
body.pos.x += body.vel.x * timestep;
body.pos.y += body.vel.y * timestep;
}
第二个循环,其中只有一个物体在移动,而且它向错误的方向移动
PVector totalForce = new PVector();
PVector fxy = new PVector();
for(int i = 0; i + 1 < bodies.size(); i++){
Body body = bodies.get(i);
Body other = bodies.get(i + 1);
System.out.println(body + " " + other);
fxy = body.attraction(other);
totalForce.x += fxy.x;
totalForce.y += fxy.y;
body.vel.x += totalForce.x / body.mass * timestep;
body.vel.y += totalForce.y / body.mass * timestep;
body.pos.x += body.vel.x * timestep;
body.pos.y += body.vel.y * timestep;
}
最佳答案
在您的第一个样本中,您正在检查每一对可能的物体。
a,b,c - (a,b),(a,c),(b,c)
在您的第二个示例中,您正在检查每个相邻的物体。
a,b,c - (a,b),(b,c)
关于Java重力循环优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49316301/