How to Disable Gravity in Matter.js
Yes, you can disable gravity entirely in Matter.js by modifying the gravity properties of your simulation's physics engine. This guide explains how to completely turn off the global gravitational force across your entire world, as well as how to neutralize gravity effects for specific scenarios using straightforward configuration settings and code examples.
Disabling Global Gravity
By default, Matter.js applies a downward gravitational pull on the
Y-axis. To remove this force completely, you need to set the
y and x components of the engine's gravity
system to 0.
You can configure this directly when creating the engine:
const engine = Matter.Engine.create({
gravity: {
x: 0,
y: 0,
scale: 0
}
});If your engine instance has already been initialized, you can update the properties directly at runtime:
// Disable vertical and horizontal gravity
engine.gravity.x = 0;
engine.gravity.y = 0;
// Alternatively, set the overall scale to zero
engine.gravity.scale = 0;Setting scale to 0 acts as a master toggle
that multiplies all directional gravity forces by zero, effectively
rendering the world completely weightless.
Disabling Gravity for Individual Bodies
Matter.js does not provide a native ignoreGravity
boolean property on individual bodies. If you want global gravity
enabled for most objects but disabled for a specific body, you can
counteract the gravitational force manually during each update tick:
Matter.Events.on(engine, 'beforeUpdate', function() {
const body = mySpecificBody;
// Calculate the counter-force
const antiGravityForce = {
x: -engine.gravity.x * engine.gravity.scale * body.mass,
y: -engine.gravity.y * engine.gravity.scale * body.mass
};
// Apply the opposing force
Matter.Body.applyForce(body, body.position, antiGravityForce);
});Alternatively, if the body should not move at all, setting
isStatic: true on the body definition will lock it in place
and make it immune to all forces, including gravity and collisions.