phaserjs/phaser/physics-matter

Claude Code and agent skill by phaserjs/phaser

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Matter Physics in Phaser 4 (Matter 0.20 and its Runner): this.matter.add (sprite, image, rectangle, circle, fromVertices, constraint, mouseSpring), shapes and PhysicsEditor data, compound bodies and sensors, collision filtering and events, the timestep, tilemap bodies, sleeping, debug drawing and the 4.3 changes. Use for rotating rigid bodies, stacking, ragdolls, chains, slopes, physics puzzles, a Matter platformer with a foot sensor, or dragging bodies. Corrects common mistakes: getDelta doesn't set the step (use runner.fps), fps.target doesn't cap the frame rate, a sleeping body ignores setVelocity, setOnCollide never fires for compound bodies. Triggers on: matter, matter.js, rigid body, constraint, joint, spring, sensor, compound body, collisionstart, PhysicsEditor, ragdoll.

Install

npx vskill@latest install phaserjs/phaser/physics-matter

SKILL.md

The same SKILL.md was published earlier as phaserjs/phaser/physics-matter.

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

js
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 by scale (0.001). At runtime: this.matter.world.setGravity(x, y, scale), disableGravity(). Per body: setIgnoreGravity(true), or gravityScale: { 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.

js
// 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() and set30Hz() set runner.delta, the same as runner: { fps }. Before 4.3 they did nothing. The getDelta config and World property aren't used any more: don't set them.
  • To step it yourself, set autoUpdate: false and call this.matter.step(delta) from update. It ignores enabled and autoUpdate.
  • Pause with this.matter.pause() and resume(). Slow motion: this.matter.world.engine.timing.timeScale = 0.5, or timing: { 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, or this.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.js and MatterRunnerConfig.js. A Scene's own physics.matter config is merged over the game's.

Bodies and shapes

js
// 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, setTrapezoid and setBody make 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, angle or scale on 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.

js
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.body is Matter.Body and this.matter.bodies is Matter.Bodies. All Matter modules are on Phaser.Physics.Matter.Matter too.
  • The position of a compound body is its centre of mass. setExistingBody sets the sprite's origin to match.
  • Options passed to Body.create go 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:

js
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.bodyA and pair.bodyB are parts, in no set order. Use .label to tell them apart, .parent for the whole body, .gameObject for its Game Object (undefined if it has none), and pair.collision.normal and depth for the contact.
  • setOnCollide(cb), setOnCollideActive, setOnCollideEnd (callback gets pair) and setOnCollideWith(bodyOrGameObject, cb) (gets otherBody, 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.speed and angularSpeed read 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.

js
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.
  • nextCategory and nextGroup use a counter shared by every Scene, which isn't reset when a Scene restarts. Create them once, or call this.matter.world.resetCollisionIDs() before making them in create.
  • A sensor (isSensor: true or setSensor(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) and overlap(target, bodies, callback) query bodies without a collision.

Constraints, composites and dragging

js
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. length defaults to the current distance. stiffness 1 is rigid; low values are springy.
  • Composites: stack, imageStack, pyramid, chain, mesh, softBody, car and newtonsCradle, in Factory.js.
  • Drag events on the World: DRAG_START (body, part, constraint), DRAG (body, constraint), DRAG_END (body, constraint). ignorePointer: true stops a body being dragged.

Tilemaps

js
// 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.matterBody is the TileBody wrapper; its body is the Matter body. After changing tiles, convert them with this.matter.world.convertTiles(tiles) or this.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

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 95 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
39,633
Repository forks
7,130
7-day trend score
53

Stars and forks are for the whole GitHub repository, not this skill alone. Refreshed 17 May 2026, 6 months ago.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Grok Build (Cursor)
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/phaserjs/phaser/physics-matter/badge)](https://verified-skill.com/skills/phaserjs/phaser/physics-matter)

Something wrong with this skill or its page? Tell us.