Wednesday, June 26, 2013

Start Your Day with Verlet

Verlet integration.  What is it, even?

Well, once upon a time, I would give my moving objects the following components:  Location, Velocity, Acceleration, Drag.  Then, each cycle, assuming 's' is seconds elapsed, I would do this:

velocity += acceleration * s * s;
velocity -= velocity * drag;
location += velocity * s;

And that worked well enough as a model.

Now, instead, I have Location, PriorLocation, Acceleration, and Drag, and lastS is the s from the previous cycle, and I do this:

Vector2 velocity = (location - priorLocation) * (s / lastS);
velocity -= velocity * drag;
priorLocation = location;
location = location + velocity + (acceleration * s * s);

Why make the change?  At first glance, it appears to be doing the same thing, but in a much more complicated fashion.

The answer is it's simpler in the long run.  Because the velocity is calculated on the fly from the positions of the entities, I can freely move entities around as a result of springs, or collisions, or whatever other reasons, and I need not change the velocity of the entity at all -- it is automatically changed.

The technical answer is it's also much more accurate.  But that's not often a germane issue in game programming.  Physical accuracy in games is a choice that you make or not, according to your purposes.

No comments:

Post a Comment