Understanding how Matter.js constraints work with Phaser

I was wondering how to properly handle constraints in the Fling prototype when I probably came to a solution:

Basically a constraint is a rule which must be followed. In our case, the rule is “keep a certain distance between two bodies”. It seems quite an easy rule to follow, but what happens when the only way to keep the required distance causes two bodies to compenetrate?

Here we have a dilemma: keeping the distance and letting a body trespass another body or act as they were solid bodies – and actually they are – and break the constraint?

Look at this example: we have three static bodies at the top, three dynamic bodies at the bottom, three distance constraints with a little stiffness and a big static body in the middle of the screen.

What happens when we reduce the distance?

From left to right:

1 – the body trespasses the other body to satisfy the constraint. I simply contract the constraint and do not care about the rest. This is Matter.js default way of handling constraints.

2 – the constraint breaks. Each time I contract the constraint, I check constraint length with actual distance between the two bodies. If they differ, the constraint is removed.

3 – the constraint does not break and does not let the body trespass solid bodies. In this case too, each time I contract the constraint, I check constraint length with actual distance between the two bodies, but this time if they differ, constraint lenght is updated to match actual distance between the bodies.

Look at the source code:

let game;
window.onload = function() {

    // game configuration
    let gameConfig = {
        type: Phaser.AUTO,
        scale: {
            mode: Phaser.Scale.FIT,
            autoCenter: Phaser.Scale.CENTER_BOTH,
            parent: "thegame",
            width: 1334,
            height: 750
        },
        scene: playGame,
        physics: {
            default: "matter",
            matter: {
                gravity: {
                    y: 1
                },
                debug: true,
                debugBodyColor: 0xff00ff,
                debugWireframes: false
            }
        }
    }
    game = new Phaser.Game(gameConfig);
    window.focus();
}
class playGame extends Phaser.Scene{
    constructor(){
        super("PlayGame");
    }
    create(){
        this.matter.world.update30Hz();
        this.matter.world.setBounds(10, 10, game.config.width - 20, game.config.height - 20);
        let poly = this.matter.add.rectangle(game.config.width / 2, game.config.height / 2, game.config.width, 50, {
            isStatic: true
        });
        this.topBodies = [];
        this.bottomBodies = [];
        this.constraints = [];
        for(let i = 1; i <= 3; i++){
            this.topBodies.push(this.matter.add.rectangle( game.config.width / 4 * i, 50, 20, 20, {
                isStatic: true
            }));
            this.bottomBodies.push(this.matter.add.rectangle( game.config.width / 4 * i, 730, 20, 20));
            let distance = Phaser.Math.Distance.Between(this.topBodies[i - 1].position.x, this.topBodies[i - 1].position.y, this.bottomBodies[i - 1].position.x, this.bottomBodies[i - 1].position.y);
            this.constraints.push(this.matter.add.constraint(this.bottomBodies[i - 1], this.topBodies[i - 1], distance, 0.1));
        }
    }
    update(){
        this.constraints[0].length -= 2;
        if(this.constraints[0].length < 0){
            this.scene.start("PlayGame")
        }
        this.constraints[1].length -= 2;
        if((Math.abs(Phaser.Math.Distance.Between(this.topBodies[1].position.x, this.topBodies[1].position.y, this.bottomBodies[1].position.x, this.bottomBodies[1].position.y) - this.constraints[1].length)) > 4){
            this.matter.world.removeConstraint(this.constraints[1]);
        }
        this.constraints[2].length -= 2;
        if((Math.abs(Phaser.Math.Distance.Between(this.topBodies[2].position.x, this.topBodies[2].position.y, this.bottomBodies[2].position.x, this.bottomBodies[2].position.y) - this.constraints[2].length)) > 4){
            this.constraints[2].length = Phaser.Math.Distance.Between(this.topBodies[2].position.x, this.topBodies[2].position.y, this.bottomBodies[2].position.x, this.bottomBodies[2].position.y)
        }
    }
};

Which one should you use? It’s up to you, according to your needs. Download the source code.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

214 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers