Java重力循环优化

时间:2018-03-16 08:38:24

标签: java loops

为什么在第二个循环示例中身体似乎被打破,我正在尝试优化我的行星系统以支持更多的身体。

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;
}

gravity example

2 个答案:

答案 0 :(得分:2)

在你的第一个样本中,你正在检查每一对可能的身体。

  

a,b,c - (a,b),(a,c),(b,c)

在你的第二个例子中,你正在检查每个邻近的身体。

  

a,b,c - (a,b),(b,c)

答案 1 :(得分:1)

似乎代码并未应用影响身体的所有力量。

Body body = bodies.get(i);
Body other = bodies.get(i + 1);

这两行是可疑的,必须考虑更多。

数学this wikipedia linkthis SO community wiki可以帮助您优化。

所以,可能的候选人是:

n=num_of_bodies;
for(int i=0;i<n-1;++i)
{
    for(int j=i+1;j<n;++j)
    {
        final Body body=bodies.get(i);
        final Body other=bodies.get(j);
        PVector fxy = body.attraction(other);
        float c=timestep/body.mass;
        body.vel.x+=fxy.x*c;
        body.vel.y+=fxy.y*c;

        c=-timestep/other.mass;
        other.vel.x+=fxy.x*c;
        other.vel.y+=fxy.y*c;

    }
}
for(Body body:bodies)
{
    body.pos.x+=body.vel.x*timestep;
    body.pos.y+=body.vel.y*timestep;
}

重点是减少对身体和其他人的重复钙。   如果指数错误,请编辑我的。