“Way of an idea” prototype ported to HTML5 using Phaser and Matter physics

Read all posts about "" game

Earlier this week I showed you a physics engine with no physics, now it’s time to bring some good real physics in game development so here I am with the HTML5 port of “Way of an Idea“, a Flash physics game released back in 2009.

You have to draw a platform to make the ball reach the goal.

Look at the game:

Draw a platform with the mouse, once you stop drawing the ball will start to move. The game restarts if you hit the goal or if the ball falls off the bottom of the screen.

I also provided a completely commented source code:

let game;
let gameOptions = {

    // minimum length of a segment, in pixels
    segmentLength: 10
}
window.onload = function() {
    var gameConfig = {
        type: Phaser.AUTO,
        backgroundColor: 0xf5f5f5,
        scale: {
            mode: Phaser.Scale.FIT,
            autoCenter: Phaser.Scale.CENTER_BOTH,
            parent: "thegame",
            width: 640,
            height: 480
        },
        physics: {
            default: "matter",
            matter: {
                debug: true
            }
        },
        scene: playGame
    }
    game = new Phaser.Game(gameConfig);
}
class playGame extends Phaser.Scene{
    constructor(){
        super("PlayGame");
    }
    create(){

        // is the player drawing?
        this.isDrawing = false;

        // has the ball been added?
        this.ballAdded = false;

        // this is the ball. I am lazy so I didn't use a sprite :)
        this.ballGraphics = this.add.graphics();
        this.ballGraphics.fillStyle(0xff0000, 1);
        this.ballGraphics.fillCircle(30, 30, 20);

        // this is the goal
        this.matter.add.rectangle(game.config.width - 30, game.config.height - 30, 20, 20, {
            isStatic: true,
            label: "goal"
        });

        // listeners
        this.input.on("pointerdown", this.startDrawing, this);
        this.input.on("pointerup", this.stopDrawing, this);
        this.input.on("pointermove", this.draw, this);

        // listener for collisions
        this.matter.world.on("collisionstart", function(event, bodyA, bodyB){

            // if the ball and the goal collide...
            if((bodyA.label == "ball" && bodyB.label == "goal") || (bodyB.label == "ball" && bodyA.label == "goal")){

                // ... restart the game
                this.scene.start("PlayGame")
            }
        }.bind(this));
    }

    // when we start drawing
    startDrawing(e){

        // the player is drawing
        this.isDrawing = true;

        // current drawing point
        this.startDrawingPoint = new Phaser.Math.Vector2(e.position);
    }

    // when we stop drawing
    stopDrawing(){

        // player is no longer drawing
        this.isDrawing = false;

        // remove the ball
        this.ballGraphics.clear();

        // if the physics ball hasn't already be added...
        if(!this.ballAdded){

            // the ball is added
            this.ballAdded = true;

            // add the ball itself
            this.dynamicBall = this.matter.add.circle(30, 30, 20, {
                friction: 0,
                restitution: 1,
                label: "ball"
            });
        }
    }

    // when we are drawing
    draw(e){

        // is the player drawing?
        if(this.isDrawing){

            // calculate the distance between start drawing point and current position
            let distance = this.startDrawingPoint.distance(e.position);

            // is the distance greater than the minimum segment length?
            if(distance > gameOptions.segmentLength){

                // create a line between start drawing point and current position
                let line = new Phaser.Geom.Line(this.startDrawingPoint.x, this.startDrawingPoint.y, e.position.x, e.position.y);

                // get the center of the line
                let center = Phaser.Geom.Line.GetPoint(line, 0.5);

                // get the angle of the line
                let angle = Phaser.Geom.Line.Angle(line);

                // add a static rectangle matching the line
                this.matter.add.rectangle(center.x, center.y, distance, 5, {
                    isStatic: true,
                    angle: angle,
                    friction: 0,
                    restitution: 1
                });

                // update start drawing point
                this.startDrawingPoint.x = e.position.x;
                this.startDrawingPoint.y = e.position.y;
            }
        }
    }

    update(){

        // if the physics ball has been added...
        if(this.ballAdded){

            // if the ball falls down the screen...
            if(this.dynamicBall.position.y > game.config.height){

                // ... restart the game
                this.scene.start("PlayGame")
            }
        }
    }
}

Building this prototype was very easy thanks to Phaser and Matter physics. Next time I’ll show you how to delete the path, meanwhile 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