How to Set Linear Velocity in Planck.js?
Planck.js is a 2D physics engine for JavaScript (a rewrite of Box2D)
where moving objects are represented as bodies. To manually set the
speed and direction of a body without relying purely on environmental
forces like gravity or collisions, you must directly modify its linear
velocity vector. This article explains how to configure a body for
velocity changes, how to use the setLinearVelocity method,
and the common pitfalls to avoid when manually controlling physics
bodies.
Step 1: Ensure the Body Type is Correct
Before you can manipulate the velocity of a body, ensure it is not a static body. Static bodies are designed to remain completely stationary and will ignore velocity changes. You must define your body as either dynamic (affected by forces and collisions) or kinematic (moved purely by velocity).
// Creating a dynamic body
const body = world.createBody({
type: 'dynamic', // or 'kinematic'
position: pl.Vec2(0, 0)
});Step 2: Use the setLinearVelocity Method
Planck.js provides a built-in method called
setLinearVelocity() on the body object. This method accepts
a 2D vector (pl.Vec2) representing the velocity along the X
and Y axes.
// Set the linear velocity (X = 5, Y = -10)
body.setLinearVelocity(pl.Vec2(5.0, -10.0));Alternatively, you can pass an existing vector object or modify the velocity based on its current vector components:
// Get the current velocity
const currentVelocity = body.getLinearVelocity();
// Keep the horizontal speed but stop vertical movement
body.setLinearVelocity(pl.Vec2(currentVelocity.x, 0.0));Best Practices and Considerations
- Physics Overrides: Manually setting the velocity overrides any natural physics calculations for that frame. If you call this method inside your main game loop every frame, the body will resist external forces like gravity and impulses from collisions.
- Kinematic vs. Dynamic: If you want an object (like
a moving platform or a user-controlled paddle) to move at a constant
velocity and completely ignore gravity or mass, use a
kinematicbody type. - Units of Measurement: Planck.js uses the MKS system (meters, kilograms, and seconds). Velocity is calculated in meters per second, not pixels per second. Ensure your rendering scale accounts for this conversion.