Matter Physics
Rigid-body physics with rotation, any convex or concave shape, constraints and composites. Phaser 4 bundles Matter 0.20.0 and steps it with the Matter Runner.
Source: src/physics/matter-js/ (MatterPhysics.js, World.js, Factory.js, components/, typedefs/, events/, MatterTileBody.js), and the Matter library in src/physics/matter-js/lib/. Related: physics-arcade, tilemaps, game-setup-and-config.
Quick start
class Game extends Phaser.Scene
{
create ()
{
const { width, height } = this.scale;
this.matter.world.setBounds(); // static walls around the game size
this.matter.add.rectangle(width / 2, height - 20, width, 40, { isStatic: true, label: 'ground' });
this.matter.add.image(500, 100, 'crate');
this.matter.add.image(560, 0, 'ball', null, { shape: 'circle', restitution: 0.8 });
this.player = this.matter.add.sprite(200, 300, 'hero');
this.player.setFixedRotation(); // don't tip over
this.cursors = this.input.keyboard.createCursorKeys();
}
update ()
{
const { left, right } = this.cursors;
this.player.setVelocityX(left.isDown ? -5 : right.isDown ? 5 : 0);
}
}
new Phaser.Game({
type: Phaser.AUTO,
width: 1024,
height: 768,
physics: {
default: 'matter',
matter: { gravity: { y: 1 }, debug: true }
},
scene: Game
});
Units and timing
- Positions are in pixels and angles in radians. Velocity is in pixels per step of 1000/60 ms, Matter's base delta, whatever the step size, so
setVelocityX(5)is about 300 pixels per second. - Forces are tiny:
applyForce({ x: 0.01, y: 0 })is a firm push for a 32x32 body at the default density of 0.001. gravity: { x: 0, y: 1 }is multiplied byscale(0.001). At runtime:this.matter.world.setGravity(x, y, scale),disableGravity(). Per body:setIgnoreGravity(true), orgravityScale: { x, y }in the body config, which works again since 4.3.
The step. World.update uses the Matter Runner. It steps the Engine in fixed slices of runner.delta (default 1000/60 ms) to match the real time that has passed, smoothed, and up to runner.maxFrameTime (33.3 ms) of simulation per frame. The simulation runs at the same speed at any frame rate. On a 120Hz display it steps about every other frame.
// Game or Scene config: a 120Hz physics step
physics: { default: 'matter', matter: { runner: { fps: 120 } } }
// At runtime
this.matter.world.runner.delta = 1000 / 120;
this.matter.set60Hz()andset30Hz()setrunner.delta, the same asrunner: { fps }. Before 4.3 they did nothing. ThegetDeltaconfig and World property aren't used any more: don't set them.- To step it yourself, set
autoUpdate: falseand callthis.matter.step(delta)fromupdate. It ignoresenabledandautoUpdate. - Pause with
this.matter.pause()andresume(). Slow motion:this.matter.world.engine.timing.timeScale = 0.5, ortiming: { timeScale: 0.5 }in the config. - The game's frame rate:
fps: { target: 60 }in the game config doesn't cap it.fps: { limit: 60 }does, orthis.game.loop.setFPSLimit(60)at runtime. Matter doesn't need either to run at the right speed. - Other config keys and their defaults:
src/physics/matter-js/typedefs/MatterWorldConfig.jsandMatterRunnerConfig.js. A Scene's ownphysics.matterconfig is merged over the game's.
Bodies and shapes
// Game Objects with a body. The default body is a rectangle the size of the frame.
this.matter.add.sprite(100, 100, 'hero', null, { shape: { type: 'circle', radius: 24 } });
this.matter.add.image(200, 100, 'gem', null, { shape: { type: 'polygon', sides: 6, radius: 32 } });
this.matter.add.image(300, 100, 'ship', null, { shape: { type: 'fromVerts', verts: '0 0 40 0 40 40 20 60 0 40' } });
// PhysicsEditor: this.load.json('shapes', 'shapes.json') in preload
this.matter.add.sprite(400, 100, 'banana', null, { shape: this.cache.json.get('shapes').banana });
// Add a body to any existing Game Object
this.matter.add.gameObject(this.add.rectangle(500, 300, 80, 20, 0x00ff00), { isStatic: true });
// Bodies with no Game Object (drawn only by the debug renderer)
this.matter.add.circle(600, 100, 20, { restitution: 0.9 });
this.matter.add.fromVertices(700, 100, '0 0 60 0 30 40 60 80 0 80'); // concave shapes are decomposed
- Body config keys (
typedefs/MatterBodyConfig.js):label,isStatic,isSensor,density(0.001),friction(0.1),frictionStatic(0.5),frictionAir(0.01),restitution(0),chamfer: { radius },collisionFilter,ignoreGravity,ignorePointer,shape. - Game Object methods come from
components/:setVelocity,setAngularVelocity,applyForce,thrust,setBounce,setFriction(value, air, static),setMass,setDensity,setStatic,setSensor,setFixedRotation,setIgnoreGravity, the collision setters and the shape setters. setRectangle,setCircle,setPolygon,setTrapezoidandsetBodymake a new body, so friction, filters and callbacks set before are lost. Set them again.setFixedRotation()stops rotation and zeroes the angular velocity. Since 4.3,setFixedRotation(false)lets the body rotate again.- Setting
x,y,angleorscaleon a Matter Game Object moves or scales the body directly, without velocity. A negative scale on one axis, to flip it, collides correctly since 4.3.
Compound bodies and a foot sensor
A compound body is one body made of parts. Each part has the Game Object as its gameObject, and its own label, so a collision tells you which part was hit.
const player = this.matter.add.sprite(0, 0, 'hero');
const { width: w, height: h } = player;
const main = this.matter.bodies.rectangle(0, 0, w * 0.6, h, { chamfer: { radius: 8 } });
const foot = this.matter.bodies.rectangle(0, h / 2, w * 0.4, 4, { isSensor: true, label: 'foot' });
player.setExistingBody(this.matter.body.create({ parts: [ main, foot ], friction: 0.01 }))
.setFixedRotation()
.setPosition(200, 300); // the sprite moves to wherever the parts were made, so place it after
this.groundContacts = 0;
player.on('collide', (myBody, other) => { if (myBody.label === 'foot' && !other.isSensor) { this.groundContacts++; } });
player.on('collideEnd', (myBody, other) => { if (myBody.label === 'foot' && !other.isSensor) { this.groundContacts--; } });
// In update(): if (jumpPressed && this.groundContacts > 0) { player.setVelocityY(-10); }
this.matter.bodyisMatter.Bodyandthis.matter.bodiesisMatter.Bodies. All Matter modules are onPhaser.Physics.Matter.Mattertoo.- The position of a compound body is its centre of mass.
setExistingBodysets the sprite's origin to match. - Options passed to
Body.creatego on the parent. Contacts use the parent's friction and restitution. - Attach constraints to the parent body, not to a part.
Collision events
On a Game Object, as plain strings: 'collide', 'collideActive' and 'collideEnd', with (myBody, otherBody, pair). myBody is the part of this object that was hit. This is the simplest way to react to collisions, and works for compound bodies.
On the World, using Phaser.Physics.Matter.Events: COLLISION_START, COLLISION_ACTIVE and COLLISION_END, with (event, bodyA, bodyB). bodyA and bodyB are from only one of the pairs, so loop over event.pairs:
this.matter.world.on(Phaser.Physics.Matter.Events.COLLISION_START, (event) => {
for (const pair of event.pairs)
{
const labels = [ pair.bodyA.label, pair.bodyB.label ];
if (labels.includes('player') && labels.includes('spikes'))
{
this.scene.restart();
}
}
});
pair.bodyAandpair.bodyBare parts, in no set order. Use.labelto tell them apart,.parentfor the whole body,.gameObjectfor its Game Object (undefined if it has none), andpair.collision.normalanddepthfor the contact.setOnCollide(cb),setOnCollideActive,setOnCollideEnd(callback getspair) andsetOnCollideWith(bodyOrGameObject, cb)(getsotherBody, pair) are set on the parent body. For a compound body they never fire, because pairs hold its parts: use the Game Object events.- The World removes its listeners when the Scene shuts down.
- Since 4.3,
body.speedandangularSpeedread during a collision event are from the end of the previous step.
Collision filtering and sensors
collisionFilter is { category: 1, mask: 0xFFFFFFFF, group: 0 } by default, so everything collides with everything.
const PLAYER = this.matter.world.nextCategory(); // 2, 4, 8 ... (32 in all)
const ENEMY = this.matter.world.nextCategory();
this.player.setCollisionCategory(PLAYER).setCollidesWith([ 1, ENEMY ]);
// Bodies in the same negative group never collide with each other; the same positive group always do
const ragdoll = this.matter.world.nextGroup(true);
this.matter.add.circle(300, 100, 16, { collisionFilter: { group: ragdoll } });
- Two bodies with different or zero groups collide only if each one's mask includes the other's category.
nextCategoryandnextGroupuse a counter shared by every Scene, which isn't reset when a Scene restarts. Create them once, or callthis.matter.world.resetCollisionIDs()before making them increate.- A sensor (
isSensor: trueorsetSensor(true)) is never pushed, but still sends collision events, and still needs a matching filter. this.matter.intersectPoint(x, y),intersectRect,intersectRay(x1, y1, x2, y2),intersectBody(body)andoverlap(target, bodies, callback)query bodies without a collision.
Constraints, composites and dragging
const boxA = this.matter.add.image(400, 200, 'crate');
const boxB = this.matter.add.image(500, 200, 'crate');
this.matter.add.constraint(boxA, boxB, 100, 1); // rigid; aliases joint and spring
this.matter.add.spring(boxA, boxB, 80, 0.02, { damping: 0.05, pointA: { x: 20, y: 0 } });
const lamp = this.matter.add.image(512, 150, 'lamp');
this.matter.add.worldConstraint(lamp, 120, 0.9, { pointA: { x: 512, y: 0 } }); // hangs from a world point
this.matter.add.mouseSpring(); // drag bodies with the pointer; alias pointerConstraint
- Constraints take bodies or Matter Game Objects.
lengthdefaults to the current distance.stiffness1 is rigid; low values are springy. - Composites:
stack,imageStack,pyramid,chain,mesh,softBody,carandnewtonsCradle, inFactory.js. - Drag events on the World:
DRAG_START (body, part, constraint),DRAG (body, constraint),DRAG_END (body, constraint).ignorePointer: truestops a body being dragged.
Tilemaps
// map and tileset as in the Quick start of the tilemaps skill
const layer = map.createLayer('Ground', tileset);
layer.setCollisionByProperty({ collides: true }); // mark the tiles first
this.matter.world.convertTilemapLayer(layer); // one static body per colliding tile
- A tile with collision shapes drawn in Tiled's collision editor uses them; otherwise it gets a rectangle.
- Since 4.3, the body of a tile flipped or rotated in Tiled is flipped and then rotated with it.
tile.physics.matterBodyis the TileBody wrapper; itsbodyis the Matter body. After changing tiles, convert them withthis.matter.world.convertTiles(tiles)orthis.matter.add.tileBody(tile, options).- A body sliding along a row of tile bodies can catch on the seams between them. Give it a
chamfer. - See tilemaps for loading the map.
Sleeping
enableSleeping: true in the config lets bodies at rest sleep. A sleeping body ignores setVelocity and forces until it wakes: call setAwake() first, or don't let player-controlled bodies sleep. setSleepThreshold(n) sets how many still steps it takes (default 60). SLEEP_START and SLEEP_END need setSleepEvents(true, true).
Debug drawing
debug: true, or a config object: showBody, showStaticBody, showSensors, showVelocity, showCollisions, showAngleIndicator, showSleeping, showInternalEdges, colours and more in typedefs/MatterDebugConfig.js. Since 4.3, a compound body, such as a concave PhysicsEditor shape, is outlined along its external edges only, unless showInternalEdges is on. To hide it at runtime, set this.matter.world.drawDebug = false and call this.matter.world.debugGraphic.clear(). this.matter.world.setBodyRenderStyle(body, lineColor, lineOpacity, lineThickness, fillColor, fillOpacity) styles one body.
4.3 behaviour changes
restingThreshandrestingThreshTangentnow default to 2 and about 2.449, matching Matter, so bodies withrestitutionbounce for much longer. For the old feel:matter: { restingThresh: 4, restingThreshTangent: 6 }.- Compound and concave bodies have the correct moment of inertia, so they rotate differently.
gravityScaleworks again. Bodies which set it fall at a different speed.- Negative scale,
setFixedRotation(false), tile body rotation,set60Hzand the debug outline are fixed, as above.setSleepEvents(false, false)no longer throws.
Gotchas
- Friction between two bodies is the lower of their two values; restitution and static friction are the higher.
- Matter's mask defaults to all bits, so a new category still collides with everything. Arcade is the other way round.
- Very fast, small bodies can tunnel through thin ones. Make walls thicker, or raise
runner.fps. - A Matter Game Object in a Container is drawn with the Container's transform, but its body ignores it, so the two drift apart. Keep Matter Game Objects out of Containers.
