Setting up Verlet

8 0 0
                                    

Verlet integration is just another method of integrating Newton's Laws of Motion into your projects. It's known for its stability in simulations. This section covers setting up a basic project with particles that use (a position based) Verlet to move.

First, you need to setup a scene. Generally, a scene consists of a list of particles. Each particle requires:
X and Y coordinates (2d vector)
The last X and Y coordinates (2d vector)
Acceleration (2d vector)
Inverse mass (scalar, 0 inverse mass represents infinite mass)

So the code might look like:
//setup rendering + other stuff
//particle object
struct particle {
position:vec2d,
last_position:vec2d,
acceleration:vec2d,
inverse_mass:double,
}
particles:list = {}

func new_particle (x:double, y:double, mass:double) {
particles.push(particle)
c_particle:particle = particles[len(particles)]
c_particle.position.x = x
c_particle.position.y = y
c_particle.last_position.x = x
c_particle.last_position.y = y
c_particle.acceleration = vector.zero
if mass == 0.0 {
c_particle.inverse_mass = 0.0
} else { c_particle.inverse_mass = 1.0/mass; }
}
//load particles
//rendering code and update code stuff
//end of code section

With your particles setup, I'd recommend representing them with dots so you can actually see them. Now it's time to actually integrate Verlet into your simulation. Verlet integration is very simple. It follows:
Velocity = Position - Last Position
Position = Position + Velocity + Acceleration * (Delta Time)^2 // delta time is just the difference in time between each time step/physics update in seconds

Implementing it may look like:
func physics_update(delta_time) {
foreach particle in particles {
velocity:vec2d = particle.position - particle.last_position
particle.last_position = particle.position //not a reference, a direct copy. Make absolute sure you don't set it to reference position.
particle.position = particle.position + particle.velocity + particle.acceleration * dt*dt
particle.acceleration = vector.zero //reset x and y to both be 0,0
}
}

To add gravity, add a constant value to acceleration before updating the particle:

#define gravity [some gravity value]
foreach particle in particles {
particle.acceleration.y += gravity
//rest of code
}

Now, to actually use the code, simply run the physics update every frame with delta time being the inverse (1/x) of the frames per second, or the change in time since the last run physics update in seconds. A loop may look like:

//update stuff
func main ()
//setup stuff
time:double
end:double = getTime()
while true {
time = getTime()
physics_update(end-time)
end = getTime()
//render + other stuff
}
}

With this done, you should have a basic falling particle simulation. The next part covers simple constraints, which really show the power of Verlet.

Physics Simulations using Verlet IntegrationWhere stories live. Discover now