“Fling” Unity game built in HTML5 with Phaser and Matter.js updated with the latest constraints tweaks – fly through the screen with your ninja rope

Read all posts about "" game

This week I showed you a HTML5 prototype of “Fling” game built with Phaser and Matter.js but it was flawed by varios Matter.js issues.

Actually we can’t talk about “issues” because it was me trying to force the way Matter.js handles the constraints, but in the end I wasn’t satisfied.

So I studied a bit how constraints work and wrote about three ways to deal with constraints.

Finally I sorted out things and now I got something enjoyable:

Click the mouse to fire the hook towards mouse pointer, click again when swinging to release it, then click again to fire another hook and pretend to be Spider-Man.

This is the updated source code:

let game;
let gameOptions = {
    gravity: 1,             // game gravity
    terrainObjects: 20,     // amount of terrain objects
    heroSize: 20,           // hero size
    constraintSpeed: 2,     // constraint shrinkage speed
    minBoxSize: 50,         // minimum box size
    maxBoxSize: 200,        // maximum box size
    hookSpeed: 20,          // speed use to fire the hook
    ropeTolerance: 6        // rope tolerance. Used to avoid body trespassing
}
const WALL = 0;
const BALL = 1;
const HOOK = 2;
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: gameOptions.gravity
                },
                debug: true
            }
        }
    }
    game = new Phaser.Game(gameConfig);
    window.focus();
}
class playGame extends Phaser.Scene{
    constructor(){
        super("PlayGame");
    }
    create(){

        // I want physics world to be updated 30 times per second
        this.matter.world.update30Hz();

        // adding world bounds. Basically four walls
        this.matter.world.setBounds(10, 10, game.config.width - 20, game.config.height - 20);

        // placing some random static boxes labeled as WALL
        for (let i = 0; i < gameOptions.terrainObjects; i++){
            let posX = Phaser.Math.Between(0, game.config.width);
            let posY = Phaser.Math.Between(0, game.config.height);
            let width = Phaser.Math.Between(gameOptions.minBoxSize, gameOptions.maxBoxSize);
            let height = Phaser.Math.Between(gameOptions.minBoxSize, gameOptions.maxBoxSize);
            let poly = this.matter.add.rectangle(posX, posY, width, height, {
                isStatic: true
            });
            poly.label = WALL;
        }

        // adding a bouncing ball labeled as BALL
        this.hero = this.matter.add.rectangle(game.config.width / 2, game.config.height / 2, gameOptions.heroSize, gameOptions.heroSize, {
            restitution: 0.5
        });
        this.hero.label = BALL;

        // the hook
        this.hook = null;

        // event listeners
        this.input.on("pointerdown", this.fireHook, this);

        // no ropes at the beginning
        this.rope = null;

        // collision listener
        this.matter.world.on("collisionstart", function(e, b1, b2){

            // when the hook collides with something, let's make it static and create the joint
            if((b1.label == HOOK || b2.label == HOOK) && !this.rope){

                // make the hook static
                Phaser.Physics.Matter.Matter.Body.setStatic(this.hook, true);

                // calculate the distance between the ball and the hook
                let distance = Phaser.Math.Distance.Between(this.hero.position.x, this.hero.position.y, this.hook.position.x, this.hook.position.y);

                // is the distance fairly greater than hero size?
                if(distance > gameOptions.heroSize * 2){

                    // add the constraint
                    this.rope = this.matter.add.constraint(this.hero, this.hook, distance, 0.1);
                }
            }
        }, this)
    }

    // method to fire the hook
    fireHook(e){

        // do we have a constraint?
        if(this.hook){

            // destroy current constraint
            this.releaseHook();
        }

        // don't we have a constraint?
        else{
            // calculate the angle between the pointer and the ball
            let angle = Phaser.Math.Angle.Between(this.hero.position.x, this.hero.position.y, e.position.x, e.position.y);

            this.hook = this.matter.add.rectangle(this.hero.position.x + (gameOptions.heroSize * 2) * Math.cos(angle), this.hero.position.y + (gameOptions.heroSize * 2) * Math.sin(angle), 10, 10);
            this.hook.label = HOOK;

            // give the hook the proper velocity
            Phaser.Physics.Matter.Matter.Body.setVelocity(this.hook, {
                x: gameOptions.hookSpeed * Math.cos(angle),
                y:gameOptions.hookSpeed * Math.sin(angle)
            });
        }
    }

    // method to remove the hook
    releaseHook(){

        // is there a constraint? Remove it
        if(this.rope){
            this.matter.world.removeConstraint(this.rope);
            this.rope = null;
        }

        // is there a hook? Remove it
        if(this.hook){
            this.matter.world.remove(this.hook);
            this.hook = null;
        }
    }

    // method to be executed at every frame
    update(){

        // is there a constraint? Shrink it
        if(this.rope){
            this.rope.length -= gameOptions.constraintSpeed;
            let hookPosition = this.hook.position;
            let heroPosition = this.hero.position;
            let distance = Phaser.Math.Distance.Between(hookPosition.x, hookPosition.y, heroPosition.x, heroPosition.y);
            if(distance - this.rope.length > gameOptions.ropeTolerance){
                this.rope.length = distance;
            }
            this.rope.length = Math.max(this.rope.length, gameOptions.heroSize * 2);
        }
    }
};

Just like in the 3rd example in the post Understanding how Matter.js constraints work with Phaser if the actual distance between the player and the hook differs from the constraint length, we set constraint length to such distance. 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

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