Skip to content

Verlet Physics

by Rokan on August 11th, 2009

Ever wondered how games have that perfect movement effect where the objects bump into each other and flow perfectly? There is a lot to this effect, and today we’re going to learn about the basis of it: Verlet physics.

If you’ve ever wandered into the realms of game programming, you’ll probably have used a movement code much like this pseudocode:

position = position + velocity

So, in real code, it looks like this:

x += x_velocity;
y += y_velocity;

This type of movement is known as Euler movement. In this tutorial we’re going to learn about a new type of movement: Verlet.

Verlet works like this:

position = (position * 2) - position + acceleration

To see the difference, look at this example: the ball on the left uses verlet movement, and the one on the right uses euler movement.

The code for movement is here: (‘ball1′ is the ball on the left, and ‘ball2′ is the ball on the right)

var sy;
sy = ball1._y;
ball1._y = (ball1._y * 2) - ball1.yp + gravity;
ball1.yp = sy;
ball2._y += gravity;

Gravity is predefined as ’0.1′.

As you can see, the y position of ball1 is multiplied by 2 and the previous y position is taken away. This creates the difference between the current position and the previous position – so, by simply changing the position, the movement engine generates acceleration. So, if you were to set the position of a ball to (100, 100) as (x, y); then if you set the position to (101, 100) without setting the previous position – the offset is 1 on the x axis and will be used as velocity. The ball will move 1 pixel to the right each step if you keep doing this. This is essentially what the acceleration does in the formula.

By using verlet physics, you can create ragdoll physics far more easily.

No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS