“Don’t Touch the Spikes” HTML5 prototype built with Phaser and Matter physics – adding coins

Read all posts about "" game

This 4th part of the “Don’t Touch the Spikes” HTML5 prototype built with Phaser and Matter physics will add coins to collect.

Let’s make a small recap: in the first step we saw how to bind Matter physics to Phaser images, in step 2 we created a completely playable game just rendered in debug draw, then graphic assets were added again in step 3.

Now it’s time to add a coin the player has to collect, this way:

Tap or click to jump, touch a spike and it’s game over. Collect coins to… well for the sake of collecting coins at the moment.

Coins introduce a new kind of Matter body called sensor. Sensors trigger collision events, but do not react with colliding body physically, so the player won’t bounce on the coin, and it’s exactly what we need.

Have a look at the source code, still uncommented with the new lines highlighted:

var game;
var gameOptions = {
    triangleBase: 60,
    ballSpeed: 7,
    jumpForce: 10
}
window.onload = function() {
    var gameConfig = {
       type: Phaser.AUTO,
       width: gameOptions.triangleBase * 9.5,
       height: gameOptions.triangleBase * 15.5,
       backgroundColor: 0x000000,
       scene: playGame,
       physics: {
           default: "matter",
           matter: {
               debug: true
           }
        }
    }
    game = new Phaser.Game(gameConfig);
    window.focus();
    resize();
    window.addEventListener("resize", resize, false);
}
class playGame extends Phaser.Scene{
    constructor(){
        super("PlayGame");
    }
    preload(){
        this.load.image("spike", "spike.png");
        this.load.image("wall", "wall.png");
        this.load.image("ball", "ball.png");
        this.load.image("coin", "coin.png");
    }
    create(){
        var spikeDistance = gameOptions.triangleBase * 1.25;
        this.leftSpikes = [];
        this.rightSpikes = [];
        for(var i = 0; i < 11; i++){
            if(i < 7){
                this.addSpike(gameOptions.triangleBase + i * spikeDistance, game.config.height - gameOptions.triangleBase / 2);
                this.addSpike(gameOptions.triangleBase + i * spikeDistance, gameOptions.triangleBase / 2);
            }
            this.leftSpikes.push(this.addSpike(- gameOptions.triangleBase / 4, gameOptions.triangleBase * 1.5 + i * spikeDistance));
            this.rightSpikes.push(this.addSpike(game.config.width + gameOptions.triangleBase / 4, gameOptions.triangleBase * 1.5 + i * spikeDistance));
        }
        this.addWall(gameOptions.triangleBase / 4, game.config.height / 2, gameOptions.triangleBase / 2, game.config.height, "leftwall");
        this.addWall(game.config.width - gameOptions.triangleBase / 4, game.config.height / 2, gameOptions.triangleBase / 2, game.config.height, "rightwall");
        this.addWall(game.config.width / 2, gameOptions.triangleBase / 4, game.config.width - gameOptions.triangleBase, gameOptions.triangleBase / 2, "");
        this.addWall(game.config.width / 2, game.config.height - gameOptions.triangleBase / 4, game.config.width - gameOptions.triangleBase, gameOptions.triangleBase / 2, "");
        var ballTexture = this.textures.get("ball");
        this.ball = this.matter.add.image(game.config.width / 4, game.config.height / 2, "ball");
        this.ball.setScale(gameOptions.triangleBase / ballTexture.source[0].width);
        this.ball.setBody({
            type: "circle",
            radius: gameOptions.triangleBase / 2
        });
        this.ball.setVelocity(gameOptions.ballSpeed, 0);
        this.coin = this.matter.add.image(0, 0, "coin");
        this.coin.setCircle();
        this.coin.setStatic(true);
        this.coin.body.isSensor = true;
        this.coin.body.label = "coin"
        this.coin.setScale(gameOptions.triangleBase / ballTexture.source[0].width);
        this.placeCoin();
        this.input.on("pointerdown", this.jump, this);
        this.matter.world.on("collisionstart", function (e, b1, b2) {
            if(b1.label == "spike" || b2.label == "spike"){
                this.scene.start("PlayGame");
            }
            if(b1.label == "leftwall" || b2.label == "leftwall"){
                this.setSpikes(true);
                this.ball.setVelocity(gameOptions.ballSpeed, this.ball.body.velocity.y);
            }
            if(b1.label == "rightwall" || b2.label == "rightwall"){
                this.setSpikes(false);
                this.ball.setVelocity(-gameOptions.ballSpeed, this.ball.body.velocity.y);
            }
            if(b1.label == "coin" || b2.label == "coin"){
                this.placeCoin();
            }
        }, this);
    }
    placeCoin(){
        this.coin.x = Phaser.Math.Between(game.config.width * 0.2, game.config.width * 0.8);
        this.coin.y = Phaser.Math.Between(game.config.height * 0.2, game.config.height * 0.8);
    }
    addWall(x, y, w, h, label){
        var wallTexture = this.textures.get("wall");
        var wall = this.matter.add.image(x, y, "wall", null, {
            isStatic: true,
            label: label
        });
        wall.setScale(w / wallTexture.source[0].width, h / wallTexture.source[0].width);
    }
    addSpike(x, y){
        var spikeTexture = this.textures.get("spike");
        var squareSize = gameOptions.triangleBase / Math.sqrt(2);
        var squareScale = squareSize / spikeTexture.source[0].width;
        var spike = this.matter.add.image(x, y, "spike", null, {
            isStatic: true,
            label: "spike"
        });
        spike.setScale(squareScale);
        spike.rotation = Math.PI / 4;
        return spike;
    }
    setSpikes(isRight){
        for(var i = 0; i < 11; i++){
            if(isRight){
                this.rightSpikes[i].x = game.config.width + gameOptions.triangleBase / 4;
            }
            else{
                this.leftSpikes[i].x = - gameOptions.triangleBase / 4;
            }
        }
        var randomPositions = Phaser.Utils.Array.NumberArray(0, 10);
        var numberOfSpikes = Phaser.Math.Between(3, 6);
        for(i = 0; i < numberOfSpikes; i++){
            var randomSpike = Phaser.Utils.Array.RemoveRandomElement(randomPositions);
            if(isRight){
                this.rightSpikes[randomSpike].x = game.config.width - gameOptions.triangleBase / 2;
            }
            else{
                this.leftSpikes[randomSpike].x = gameOptions.triangleBase / 2;
            }
        }
    }
    jump(){
        this.ball.setVelocity((this.ball.body.velocity.x > 0) ? gameOptions.ballSpeed : -gameOptions.ballSpeed, -gameOptions.jumpForce);
    }
    update(){
        this.ball.setVelocity((this.ball.body.velocity.x > 0) ? gameOptions.ballSpeed : -gameOptions.ballSpeed, this.ball.body.velocity.y);
    }
};
function resize(){
    var canvas = document.querySelector("canvas");
    var windowWidth = window.innerWidth;
    var windowHeight = window.innerHeight;
    var windowRatio = windowWidth / windowHeight;
    var gameRatio = game.config.width / game.config.height;
    if(windowRatio < gameRatio){
        canvas.style.width = windowWidth + "px";
        canvas.style.height = (windowWidth / gameRatio) + "px";
    }
    else{
        canvas.style.width = (windowHeight * gameRatio) + "px";
        canvas.style.height = windowHeight + "px";
    }
}

As usual, adding important features is a matter of minutes with Phaser, next time we’ll cover a scoring system and you’ll see the completely commented script, 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

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