Using Box2D Impulses to move objects.

1 vote · 0 comments

Sometimes it can be difficult to move physics bodies how you want them to. In cases where you want to move a body at a certain velocity instantly, the best way is to apply a linear impulse.

An impulse in physics deals with the force, time, and momentum of a body. Momentum is equal to the mass of an object times its velocity, or p = m*v. An impulse is equal to the change in momentum, or I = p1 - p0 = dp. This is important. Since the final momentum (p1) minus the initial momentum (p0) equals the impulse, we can simply apply the change needed in momentum as an impulse to reach the target momentum, getting us to the target velocity.

Every frame, grab the body's velocity with getLinearVelocity(), and get its current momentum by multiplying its mass with its velocity. From there, find the target momentum by multiplying the body's mass with the wanted velocity. Finally, get the change in momentum by subtracting the initial momentum from the target momentum and apply that to the body as an impulse with applyLinearImpulse().

For simplicity, since momentum is mass time velocity, we can simply work with velocities and multiply the mass when apply the impluse: p1 - p0 = m*v1 - m*v0 = m * (v1 - v0)

raw ·
· download
// Body mass and target velocity mass = 10 targetSpeed = 5 local velX, velY = body:getLinearVelocity() local ipX = mass * velX -- Initial velocity local tpX = mass * targetSpeed body:applyLinearImpulse(tpX - ipX, 0) // Or, for simplicity mass = 15 targetSpeed = 7 local velX, velY = body:getLinearVelocity() body:applyLinearImpulse(mass * (targetSpeed - velX), 0)

Be the first to comment

Sign in with OpenID