How to Apply an Impulse in Matter.js
Applying a sudden impulse to a physics body in Matter.js allows you
to simulate instantaneous forces such as jumps, explosions, or impacts.
While Matter.js does not provide a dedicated applyImpulse
function, you can achieve this effect either by applying a single-frame
force via Matter.Body.applyForce or by directly modifying
momentum using Matter.Body.setVelocity. This guide explains
both approaches, their differences, and how to implement them cleanly in
your project.
Method 1: Using
Body.applyForce
The most physically accurate way to apply an impulse is
Matter.Body.applyForce(). Because an impulse is simply a
force applied over an infinitesimal amount of time, applying a force for
a single engine update tick functions as an instantaneous impulse.
Syntax
Matter.Body.applyForce(body, position, force);body: The targetMatter.Bodyinstance.position: A 2D vector{ x, y }defining where the force is applied. Applying the force away from the body's center of mass (body.position) induces both linear acceleration and angular velocity (torque).force: A 2D vector{ x, y }defining the magnitude and direction of the force.
Example: Upward Jump with Spin
const { Body, Vector } = Matter;
// Target body
const player = Bodies.rectangle(400, 200, 50, 50);
// Apply an upward and slightly rightward impulse from the bottom edge
Body.applyForce(
player,
{ x: player.position.x - 10, y: player.position.y + 25 }, // Off-center application
{ x: 0.05, y: -0.08 } // Force vector
);Because applyForce adheres to Newton's second law (\(F = ma\)), the resulting acceleration
depends on the body's mass. If your body has a high mass or density, you
must scale the force vector proportionally to achieve the desired
velocity.
Method 2: Using
Body.setVelocity
If you want an arcade-style impulse where mass does not affect the outcome—such as a fixed-height jump in a platformer—modifying the body's velocity directly is the ideal solution.
Syntax
Matter.Body.setVelocity(body, velocity);body: The targetMatter.Bodyinstance.velocity: A 2D vector{ x, y }defining the new absolute velocity.
Example: Instant Jump
const { Body } = Matter;
// Set upward velocity while preserving existing horizontal speed
Body.setVelocity(player, {
x: player.velocity.x,
y: -12
});To add velocity relative to the current movement rather than overwriting it, add to the existing velocity vector:
Body.setVelocity(player, {
x: player.velocity.x + 5,
y: player.velocity.y - 10
});Which Method Should You Use?
- Use
Body.applyForcewhen you need realistic physics interactions. It naturally handles mass, momentum, and rotational torque if the force is applied off-center. - Use
Body.setVelocityfor character controllers, platformers, or predictable mechanics where an object should always react with the exact same speed regardless of weight or existing momentum.