360 Secure SkillHub
360 安全技能中心

physics-matter

面向 Phaser 4 的 Matter 物理参考,涵盖刚体、形状、约束、复合体、碰撞过滤、瓦片地图、休眠和调试,并纠正时间步、睡眠与复合体碰撞等常见错误。

分类:知识
phaserjs
热度 0.00
最近更新 2026-12-03 17:40:26

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add phaserjs/phaser/physics-matter
兼容性
通用兼容
联网要求
不联网
数据出网
数据不出本机
Metadata
name
physics-matter
description
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.
metadata
{"phaser-version":"4.3.0"}

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 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.

//  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

//  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.

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:

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.

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

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

//  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

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

  • restingThresh and restingThreshTangent now default to 2 and about 2.449, matching Matter, so bodies with restitution bounce 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.
  • gravityScale works again. Bodies which set it fall at a different speed.
  • Negative scale, setFixedRotation(false), tile body rotation, set60Hz and 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.