How to Set Restitution in Matter.js
This article explains how to configure and adjust the restitution—commonly referred to as bounciness or elasticity—of rigid bodies in the Matter.js 2D physics engine. You will learn what the restitution property does, how to set it during body initialization, how to update it dynamically at runtime, and how Matter.js calculates collisions between bouncing objects.
What is Restitution in Matter.js?
In Matter.js, the restitution property determines the
elasticity of a physical body during collisions. It accepts a
Number typically ranging from 0 to
1:
0(Default): Completely inelastic collision. The body will not bounce at all.1: Perfectly elastic collision. The body retains its kinetic energy and rebounds completely.- Greater than
1: Hyper-elastic collision. The body gains energy upon collision, resulting in exaggerated bounces.
Setting Restitution on Body Creation
The most common way to define restitution is by passing it inside the
options object when instantiating a body with
Matter.Bodies.
// Create a bouncy ball
const ball = Matter.Bodies.circle(100, 100, 20, {
restitution: 0.8, // 80% bounciness
friction: 0.05
});
// Add the body to the world
Matter.Composite.add(engine.world, ball);Updating Restitution on an Existing Body
If you need to change the bounciness of an object after it has
already been added to your simulation, you can modify the property
directly on the body instance or use the Body.set utility
function:
// Method 1: Direct property assignment
ball.restitution = 0.5;
// Method 2: Using Matter.Body.set
Matter.Body.set(ball, 'restitution', 0.5);How Matter.js Calculates Collision Restitution
When two bodies collide, Matter.js calculates the final bounce factor using the maximum restitution between the two interacting bodies:
\[\text{effectiveRestitution} = \max(\text{bodyA.restitution}, \text{bodyB.restitution})\]
Because the engine uses the maximum value rather than an average, a
body with a restitution of 0.9 colliding with a static
floor that has a restitution of 0 will still rebound with a
bounce factor of 0.9. If you want an object to bounce, you
only need to set the restitution value on that specific object.