简体   繁体   中英

java 2d net gravity calculation

I am trying to calculate the net acceleration due to gravity in order to build a simple space flight sim using (G*(m1 * m2) / d * d) / m1. The ship tends to go in a semi-correct direction in a stair step pattern.

The update function of the main class

    public void update()
{
    double[] accels = new double[bodies.size()];//acceleration of the planets
    double[][] xyaccels = new double[bodies.size()][2];//storing the x and y
    for(Body n: bodies){
        int count = 0;
        double dist = distance(ship.loc.x,ship.loc.y,n.loc.x,n.loc.y);
        double acel = getAccel(n.mass, ship.mass, dist);
        accels[count] = acel;
        double alpha = getAngle(ship.loc.x,ship.loc.y,n.loc.x,n.loc.y);
        //xyaccels[count][0] = Math.cos(alpha) * acel;
        //xyaccels[count][1] = Math.sin(alpha) * acel;
        //split the acceleration into the x and y
        XA += Math.cos(alpha) * acel;
        YA += Math.sin(alpha) * acel;
        count++;
    }

    ship.update(XA, YA);
    //XA = 0;
    //YA = 0;
    accels = null;
    xyaccels = null;
}

update function for the spaceship

public void update(double XA, double YA){
    xAccel += XA;
    yAccel += YA;

    //add the x-acceleration and the y-acceleration to the loc
    loc.x += Math.round(xAccel);
    loc.y += Math.round(yAccel);
}

You don't update location from acceleration. You don't have any equations relating velocity to acceleration that I can see. Your physics are wrong.

The 2D n body problem requires four coupled ordinary differential equations for each body. Acceleration, velocity, and displacement are all 2D vector quantities.

dv/dt = F/m  // Newton's F = ma 
ds/dt = v    // Definition of velocity that you'll update to get position.

You have to integrate all of them together.

I'm assuming you know something about calculus and physics. If you don't, it's a better idea to find a library written by someone else who does: something like JBox2D .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM