5

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; } 
3
  • 5
    You have to affect your point "velocityY" values by the force of gravity. Each iteration, the "velocityY" must get smaller (less positive) by some amount, and the amount itself must get bigger over time on a per-point basis. Think about the basic physics of real gravity :) Commented Jul 13, 2013 at 23:16
  • I will see what I can do :) Commented Jul 13, 2013 at 23:38
  • Oh and note that since the coordinate system on a web page is upside down, conceptually "negative" velocity is actually positive! Commented Jul 13, 2013 at 23:43

1 Answer 1

5

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).

Sign up to request clarification or add additional context in comments.

Comments