Search code examples
javascriptmathgravitynumerical-methods

JS - How can I implement gravity?


How can I implement gravity? I have made this: http://jsfiddle.net/X2XvC/5/ but all dots simply follow your cursor (that's not gravitation). I heard about Eulers method, but I don't know how to implement it into my code.

what I found:

void update(float dt)
{
    position += velocity * dt + acceleration * 0.5 * dt * dt;
    velocity += acceleration * dt;
}

Solution

  • As Pointy already suggested, you have to affect the points' velocity vector.

    Gravity is a force that is calculated by:

    F_G = gamma * mass1 * mass2 / distance^2
    

    Where gamma is the Gravitational constant and mass1 and mass2 are the objects' masses. You get the resulting acceleration with:

    F_G = a * mass1
    a = F_G / mass1
      = gamma * mass2 / distance^2
    

    And you'll see that the acceleration is independent of the moving object's mass. What remains is gamma * mass2 which you can set to an arbitrary constant. Whichever meets your needs best.

    Now we have the length of the acceleration vector. The direction is of course normalize(cursorPosition - pointPosition). So the overall acceleration is:

    d = cursorPosition - pointPosition
    a = constant * d / length(d)^3
    

    Knowing this, you can update the point's velocity and speed in every frame by:

    velocity += a * dt
    position += velocity * dt
    

    where dt is the duration of the last frame.

    Here is your changed example code. The line if(distance < 6)... is used to cap the acceleration (if a point moves through the gravity center, it is infinitely accelerated).