Build a 3D HTML5 game like “Stairs” using Phaser and Three.js – Step 4: collision detection, better controls and level progression

Read all posts about "" game

Here we go with the 4th part of the tutorial series about the creation of a “Stairs” HTML5 game using Phaser and Three.js.

In step 1 we created an endless staircase with random spikes, and in step 2 we added a bouncing ball without using any physics engine, just trigonometry, and in step 3 we saw how to control the ball with the mouse and add more spikes.

In this massive update, I am going to add collision detection, better controls using some kind of virtual trackpad and level progression.

Collision detection is determined with no physics engine, just calculating the distance from ball center to spike tip, and seeing if it’s greater or smaller than ball radius. If the distance is smaller than ball radius, then the spike pierced the ball.

As for the controls, rather than just following mouse position, I developed a virtual pad system, like in the original game, which checks for first x input position and moves the ball as you keep dragging from that first x position.

To change the levels, I just count the amount of steps climbed, then increase the speed and change step colors.

Have a look at the result:

Click and drag to move the ball, level changes each 10 steps, avoid the spikes.

This has been possible with one HTML file, one CSS file and five TypeScript files, let’s have a look at them:

index.html

The web page which hosts the game, to be run inside thegame element.

<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="initial-scale=1, maximum-scale=1">
        <link rel="stylesheet" href="style.css">
        <script src="main.js"></script> 
    </head>
    <body>   
        <div id = "thegame"></div>
    </body>
</html>

style.css

The cascading style sheets of the main web page.

* {
    padding : 0;
    margin : 0;
}

body {
    background-color: #011025;    
}

canvas {
    touch-action : none;
    -ms-touch-action : none;
}

gameOptions.ts

Configurable game options. It’s a good practice to place all configurable game options, if possible, in a single and separate file, for a quick tuning of the game.

// CONFIGURABLE GAME OPTIONS
// changing these values will affect gameplay

export const GameOptions = {

    // amount of steps to be created and recycled
    stepsAmount : 12,
 
    // staircase speed, in pixels per second
    staircaseSpeed : 70,

    staircaseSpeedIncrease : 2,

    // step size: x, y, z
    stepSize : new Phaser.Math.Vector3(400, 40, 160),

    // ball diameter, in pixels
    ballDiameter : 60,

    // ball starting step
    ballStartingStep : 2,

    // ball jump height, in pixels
    jumpHeight : 150,

    // amount of spikes per step
    spikesPerStep : 7,
    
    // margin between spikes, in pixels
    spikesMargin : 5,

    // max visible spikes per step at the same time
    maxVisibleSpikesPerStep : 4,

    // step colors
    stepPalette : [0x4deeea, 0x74ee15, 0xffe700, 0xf000ff, 0x001eff],

    // amount of steps needed before level changes
    levelChange : 10
}

main.ts

This is where the game is created, with all Phaser related options.

// MAIN GAME FILE

// modules to import
import Phaser from 'phaser';
import { PlayGame } from './playGame';

// object to initialize the Scale Manager
const scaleObject : Phaser.Types.Core.ScaleConfig = {
    mode : Phaser.Scale.FIT,
    autoCenter : Phaser.Scale.CENTER_BOTH,
    parent : 'thegame',
    width : 540,
    height : 960
}

// game configuration object
const configObject : Phaser.Types.Core.GameConfig = {
    type : Phaser.AUTO,
    backgroundColor : 0x011025,
    scale : scaleObject,
    scene : [PlayGame]
}

// the game itself
new Phaser.Game(configObject);

playGame.ts

Main game file, all game logic and Three integration is stored here.

// THE GAME ITSELF

import * as THREE from 'three';
import { GameOptions } from './gameOptions';
import { ThreeStep } from './threeStep';
import { ThreeBall } from './threeBall';

// enum to represent the game states
enum GameState {
    Waiting,
    Playing,
    Over    
}

// this class extends Scene class
export class PlayGame extends Phaser.Scene {

    // step to build the staircase
    steps : ThreeStep[];

    // the ball
    ball : ThreeBall;

    // current game state
    gameState : GameState;

    // virtual pad x position
    virtualPadX : number;

    // variable to save ball x position when we start acting on the trackpad
    ballPositionX : number;

    // amount of climbed steps
    climbedSteps : number;

    // ball speed
    speed : number;

    constructor() {
        super({
            key: 'PlayGame'
        });
    }

    // method to be executed when the scene has been created
    create() : void {

        // set the speed to default staircase speed
        this.speed = GameOptions.staircaseSpeed;

        // we start with climbedSteps = -1 because we are one step away from the first actual step
        this.climbedSteps = -1;

        // when virtual pad X is equal to -1, it means we aren't using the virtual pad
        this.virtualPadX = -1;

        // current game starte is: waiting (for player input)
        this.gameState = GameState.Waiting;

        // creation of the 3D scene
        const threeScene : THREE.Scene = this.create3DWorld();

        // add steps to the 3D scene and into steps array
        this.steps = [];
        for (let i = 0; i < GameOptions.stepsAmount; i ++) {
            this.steps.push(new ThreeStep(this, threeScene, i));
        }    

        // add the ball
        this.ball = new ThreeBall(this, threeScene);

        // wait for input start 
        this.input.on('pointerdown', this.startControlling, this);

        // wait for input end
        this.input.on('pointerup', this.stopControlling, this);
    }

    // method to build the 3D scene
    create3DWorld() : THREE.Scene {

        // variables to store canvas width and height
        const width : number = this.game.config.width as number;
        const height : number = this.game.config.height as number;

        // create a new THREE scene
        const threeScene : THREE.Scene = new THREE.Scene();

        // create the renderer
        const renderer : THREE.WebGLRenderer = new THREE.WebGLRenderer({
            canvas: this.sys.game.canvas,
            context: this.sys.game.context as WebGLRenderingContext,
            antialias: true
        });
        renderer.autoClear = false;
        renderer.shadowMap.enabled = true;
        renderer.shadowMap.type = THREE.PCFSoftShadowMap;

        // add a camera
        const camera : THREE.PerspectiveCamera = new THREE.PerspectiveCamera(45, width / height, 1, 10000);
        camera.position.set(width / 2, 720, 640);
        camera.lookAt(width / 2 , 560, 320);

        // add an ambient light
        const ambientLight : THREE.AmbientLight = new THREE.AmbientLight(0xffffff, 1);
        threeScene.add(ambientLight);
        
        // add a directional light
        const directionalLight : THREE.DirectionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
        directionalLight.castShadow = true;
        directionalLight.position.set(270, 200, 0);
        directionalLight.target.position.set(270, 100, -1000);
        threeScene.add(directionalLight);
        threeScene.add(directionalLight.target)
       
        // add a spotlight
        const spotLight : THREE.SpotLight = new THREE.SpotLight(0xffffff, 0.2, 0, 0.4, 0.5, 0.1);
        spotLight.position.set(270, 1000, 0);
        spotLight.castShadow = true;
        spotLight.shadow.mapSize.width = 1024;
        spotLight.shadow.mapSize.height = 1024;
        spotLight.shadow.camera.near = 1;
        spotLight.shadow.camera.far = 10000;
        spotLight.shadow.camera.fov = 80;
        spotLight.target.position.set(270, 0, -320);
        threeScene.add(spotLight);
        threeScene.add(spotLight.target);

        // add a fog effect
        const fog : THREE.Fog = new THREE.Fog(0x011025, 900, 2000);
        threeScene.fog = fog;

        // create an Extern Phaser game object
        const view : Phaser.GameObjects.Extern = this.add.extern();
        
        // custom renderer
        // next line is needed to avoid TypeScript errors
        // @ts-expect-error
        view.render = () => {
            renderer.state.reset();
            renderer.render(threeScene, camera);
        };        
        return threeScene;
    }

    // start controlling the ball
    startControlling(e : Phaser.Input.Pointer) : void {

        // save input x position 
        this.virtualPadX = e.position.x;

        // save current ball x position
        this.ballPositionX = this.ball.position.x;

        // if game state is "waiting" (for player input) ...
        if (this.gameState == GameState.Waiting) {

            // ... then start playing
            this.gameState = GameState.Playing;
        }
    }

    // stop controlling the ball
    stopControlling() : void {

        // set virtual pad x to its default value
        this.virtualPadX = -1;
    }

    // restart the game
    restartGame() : void {

        // start "PlayGame" scene
        this.scene.start('PlayGame');
    }

    // method to be executed at each frame 
    update(time : number, deltaTime : number) : void {

        // if we are playing...
        if (this.gameState == GameState.Playing) {

            // determine next ball x position, which is current ball x position
            let nextBallXPosition : number = this.ball.position.x;

            // if we are moving the virtual pad...
            if (this.virtualPadX != -1) {

                // adjust next ball x position according to virtual pad movmement
                nextBallXPosition = this.ballPositionX + this.game.input.activePointer.x - this.virtualPadX
            }

            // update ball position, and check if we just jumped
            let justBounced : boolean = this.ball.updateBallPosition(deltaTime, nextBallXPosition, this.speed);

            // get 3D ball coordinates
            let ballCoordinates : Phaser.Math.Vector3 = new Phaser.Math.Vector3(this.ball.position.x, this.ball.position.y, this.ball.position.z);

            // did we just bounce?
            if (justBounced) {
                this.climbedSteps ++;
            }

            // loop through steps array
            this.steps.forEach((step : ThreeStep) => {

                // adjust step position according to speed, delta time and step size
                step.position.y -= deltaTime / 1000 * this.speed;
                step.position.z += deltaTime / 1000 * this.speed * GameOptions.stepSize.z / GameOptions.stepSize.y;
            
                // if the step is leaving the game from the bottom...
                if (step.position.y < - 40) {

                    // ...place it on top of the staircase
                    step.position.y += GameOptions.stepsAmount * GameOptions.stepSize.y;
                    step.position.z -= GameOptions.stepsAmount * GameOptions.stepSize.z;

                    // randomly show step spikes
                    step.initializeStep(GameOptions.maxVisibleSpikesPerStep, GameOptions.stepsAmount + this.climbedSteps - GameOptions.ballStartingStep + 1);
                }
            })
            
            // initialize a 3D vector to store spike position
            let spikePosition : THREE.Vector3 = new THREE.Vector3;
            
            // loop through all spikes in the step we are about to land on
            this.steps[this.ball.stepIndex].spikes.forEach((spike : THREE.Mesh) => {

                // is the spike visible?
                if (spike.visible) {

                    // get spike world position
                    spike.getWorldPosition(spikePosition);

                    // determine the distance between ball center and spike
                    let ballDistance : number = ballCoordinates.distance(new Phaser.Math.Vector3(spikePosition.x, spikePosition.y + GameOptions.stepSize.y, spikePosition.z));

                    // is the distance lower than ball radius? This would mean spike's tip is inside the ball
                    if (ballDistance < GameOptions.ballDiameter / 2) {
                        
                        // it's game over!
                        this.gameState = GameState.Over;

                        // restart the game in a second
                        this.time.addEvent({
                            delay : 1000,
                            callback : this.restartGame,
                            callbackScope : this
                        });
                    }
                }
            })
           
            // if we climbed enough steps to make level change...
            if (justBounced && this.climbedSteps % GameOptions.levelChange == 0 && this.climbedSteps >= GameOptions.levelChange) {
                
                // ...increase the speed accordingly
                this.speed += GameOptions.staircaseSpeedIncrease;
            }      
        }
    }
}

threeStep.ts

Custom class extending THREE.Group to define the step, which is made of nine Three meshes: one with a box geometry for the step itself, and eight with a cone geometry for the spikes.

import { GameOptions } from './gameOptions';
import * as THREE from 'three';

// class to define the step, extends THREE.Group
export class ThreeStep extends THREE.Group {

    // array to contain all step spikes
    spikes : THREE.Mesh[];

    // the step mesh
    step : THREE.Mesh;
   
    constructor(scene : Phaser.Scene, threeScene : THREE.Scene, stepNumber : number) {
        super();
        
        // build the step
        const stepGeometry : THREE.BoxGeometry = new THREE.BoxGeometry(GameOptions.stepSize.x, GameOptions.stepSize.y, GameOptions.stepSize.z);
        const stepMaterial : THREE.MeshStandardMaterial = new THREE.MeshStandardMaterial({
            color : 0x09c4fe
        });
        this.step = new THREE.Mesh(stepGeometry, stepMaterial);
        this.step.receiveShadow = true;
        this.add(this.step);

        // determine spike radius
        let spikeRadius : number = ((GameOptions.stepSize.x - (GameOptions.spikesPerStep + 1) * GameOptions.spikesMargin) / GameOptions.spikesPerStep) / 2;

        // build the spike
        const spikeGeometry = new THREE.ConeGeometry(spikeRadius, GameOptions.stepSize.y, 32);
        const spikeMaterial = new THREE.MeshStandardMaterial({
            color: 0x444444
        });

        // build the spikes and set them to invisible
        this.spikes = [];

        // execute this loop "spikesPerStep" times
        for (let i : number = 0; i < GameOptions.spikesPerStep; i ++) {

            // build the i-th spike
            let spike = new THREE.Mesh(spikeGeometry, spikeMaterial);
            spike.position.set(i * (spikeRadius * 2 + GameOptions.spikesMargin) - GameOptions.stepSize.x / 2 + spikeRadius + GameOptions.spikesMargin, GameOptions.stepSize.y, 0);
            this.add(spike);
            this.spikes.push(spike);
            spike.visible = false;
        }

        // initialize the step
        this.initializeStep(GameOptions.maxVisibleSpikesPerStep, stepNumber);
    
        // position the group properly
        this.position.set(scene.game.config.width as number / 2, stepNumber * GameOptions.stepSize.y, stepNumber * -GameOptions.stepSize.z);

        // add the group to the scene
        threeScene.add(this);
    }

    // method to show a random amount of spikes
    initializeStep(spikesAmount : number, stepNumber : number) : void {

        // set step color
        let color : number = Math.floor((stepNumber - GameOptions.ballStartingStep - 1) / GameOptions.levelChange) % GameOptions.stepPalette.length;

        // set all spikes invisible
        this.spikes.forEach((spike : THREE.Mesh) => {
            spike.visible = false;
        });

        // is this step higher than ball starting step?
        if (stepNumber > GameOptions.ballStartingStep) {

            // repeat this loop "n" times
            for (let i : number = 0; i < spikesAmount; i ++) {

                // select a random spike and make it visible
                let spike : THREE.Mesh = Phaser.Utils.Array.GetRandom(this.spikes);
                spike.visible = true;
            }

            // set step color
            // @ts-expect-error
            this.step.material.color.setHex(GameOptions.stepPalette[color]);
        }        
    }
}

threeBall.ts

Custom class extending THREE.Mesh to define the ball.

import { GameOptions } from './gameOptions';
import * as THREE from 'three';

// class to define the ball, extends THREE.Mesh
export class ThreeBall extends THREE.Mesh {

    // amount of time the ball is in play, useful to determine its position 
    ballTime : number;

    // ball starting y position
    startY : number;

    // index of the step the ball is on
    stepIndex : number

    // ball horizontal movement range
    movementRange : number[];
   
    constructor(scene : Phaser.Scene, threeScene : THREE.Scene) {

        // build the ball
        const SphereGeometry : THREE.SphereGeometry = new THREE.SphereGeometry(GameOptions.ballDiameter / 2, 32, 32);
        const sphereMaterial : THREE.MeshStandardMaterial = new THREE.MeshStandardMaterial({
            color : 0x444444
        });
        super(SphereGeometry, sphereMaterial);

        // step index is equal to ball starting step at the moment
        this.stepIndex = GameOptions.ballStartingStep;
        
        // ball casts shadows
        this.castShadow = true;

        // ball is in time for zero milliseconds at the moment
        this.ballTime = 0;

        // determine ball starting y position according to step size, ball diameter, and ball starting step
        this.startY = (GameOptions.ballStartingStep + 0.5) * GameOptions.stepSize.y + GameOptions.ballDiameter / 2

        // position the ball properly
        this.position.set(scene.game.config.width as number / 2, this.startY , GameOptions.ballStartingStep * -GameOptions.stepSize.z);

        // set movement range to let the ball always remain on a step
        this.movementRange = [this.position.x - GameOptions.stepSize.x / 2 + GameOptions.ballDiameter / 2, this.position.x + GameOptions.stepSize.x / 2 - GameOptions.ballDiameter / 2];

        // add the group to the scene
        threeScene.add(this);
    }

    // method to update ball position according to the time the ball is in play
    updateBallPosition(delta : number, posX : number, speed : number) : boolean {

        // jump time, in seconds, is determined by y step size divided by staircase speed
        let jumpTime : number =  GameOptions.stepSize.y / speed * 1000;

        // determine ball time, being sure it will never be greater than the time required to jump on next step
        this.ballTime = (this.ballTime += delta) % jumpTime;

        if (this.ballTime <= delta) {
            this.stepIndex = (this.stepIndex + 1) % GameOptions.stepsAmount;
        }

        // ratio is the amount of time passed divided by the time required to jump on next step
        let ratio : number = this.ballTime / jumpTime;

        // set ball x position
        this.position.setX(Phaser.Math.Clamp(posX, this.movementRange[0], this.movementRange[1]));

        // set ball y position using a sine curve
        this.position.setY(this.startY + Math.sin(ratio * Math.PI) * GameOptions.jumpHeight);

        // if ballTime is less than or equal to deta time, it means the ball just bounced on a step
        return this.ballTime <= delta;
    }
}

We are almost ready to turn the prototype into a complete game, some bonus stuff and we are done. Expect the final game in a few days. Meanwhile, download the source code of the complete project.

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