Build a HTML5 game like “Color Jump” using Phaser 3 and Matter physics, introducing some ES6 features

Read all posts about "" game

Color Jump” is another quick and fun game by Ketchapp Studio available for both iOS and Android devices.

You have to jump from side to side and go as far as you can, avoiding hitting the wrong color.

Like most Ketchapp games, it’s quite easy to code, and very similar to – and simpler than – another great Ketchapp blockbuster: Don’t touch the spikes.

Look at the game:

Tap to jump. Hit the walls matching the color of the ball, or it’s game over. If you fall down, it’s game over. If you fly off the top, it’s game over.

What about ES6? ECMAScript 6 is also known as ES6 or even JavaScript 6 and introduces some new stuff to make the code look cleaner, like the let statement which allows you to declare a variable with block scope, or the const statement which allows you to declare a constant. Constants are similar to let variables, except that the value cannot be changed.

We’ll cover ES6 during next weeks, at the moment have a look at the source code, still uncommented but easy to understand.

let game;
let gameOptions = {
    ballSpeed: 4,
    jumpForce: 30,
    bars: 4,
    barColors: [0x1abc9c, 0x2980b9, 0x9b59b6, 0xf1c40f, 0xc0392b, 0xecf0f1]
}

const LEFT = 0;
const RIGHT = 1;

window.onload = function() {
    let gameConfig = {
        type: Phaser.AUTO,
        width: 750,
        height: 1334,
        backgroundColor: 0x000000,
        scene: playGame,
        physics: {
            default: "matter",
            matter: {
                gravity: {
                    x: 0,
                    y: 4
                },
                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("wall", "wall.png");
        this.load.image("ball", "ball.png");
    }
    create(){
        this.leftWalls = [];
        this.rightWalls = [];
        for(let i = 0; i < gameOptions.bars; i++){
            this.leftWalls[i] = this.addWall(i, LEFT);
            this.rightWalls[i] = this.addWall(i, RIGHT);
        }
        this.ball = this.matter.add.image(game.config.width / 4, game.config.height / 2, "ball");
        this.ball.setBody({
            type: "circle"
        });
        let randomWall = Phaser.Math.RND.pick(this.rightWalls);
        this.ball.setTint(randomWall.body.color);
        this.ball.setVelocity(gameOptions.ballSpeed, 0);
        this.input.on("pointerdown", this.jump, this);
        this.matter.world.on("collisionstart", function (e, b1, b2) {
            if(b1.label == "leftwall" || b2.label == "leftwall"){
                this.handleWallCollision(LEFT, b1, b2);
            }
            if(b1.label == "rightwall" || b2.label == "rightwall"){
                this.handleWallCollision(RIGHT, b1, b2);
            }
        }, this);
    }
    addWall(wallNumber, side){
        let wallTexture = this.textures.get("wall");
        let wallHeight = game.config.height / gameOptions.bars;
        let wallX = side * game.config.width + wallTexture.source[0].width / 2 - wallTexture.source[0].width * side;
        let wallY = wallHeight * wallNumber + wallHeight / 2;
        let wall = this.matter.add.image(wallX, wallY, "wall", null, {
            isStatic: true,
            label: (side == RIGHT) ? "rightwall" : "leftwall"
        });
        wall.displayHeight = wallHeight;
        return wall
    }
    handleWallCollision(side, bodyA, bodyB){
        if(bodyA.color != bodyB.color){
            this.scene.start("PlayGame");
        }
        this.paintWalls((side == LEFT) ? this.rightWalls : this.leftWalls);
        this.ball.setVelocity(gameOptions.ballSpeed, this.ball.body.velocity.y);
    }
    paintWalls(walls){
        walls.forEach(function(wall){
            let color = Phaser.Math.RND.pick(gameOptions.barColors);
            wall.setTint(color);
            wall.body.color = color;
        });
        let randomWall = Phaser.Math.RND.pick(walls);
        this.ball.setTint(randomWall.body.color);
        this.ball.body.color = randomWall.body.color;
    }
    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);
        if(this.ball.y < 0 || this.ball.y > game.config.height){
            this.scene.start("PlayGame");
        }
    }
};
function resize(){
    let canvas = document.querySelector("canvas");
    let windowWidth = window.innerWidth;
    let windowHeight = window.innerHeight;
    let windowRatio = windowWidth / windowHeight;
    let 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";
    }
}

Next time I’ll show you how to add coins and increase the difficulty, 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