Get the full commented source code of

HTML5 Suika Watermelon Game

Talking about Block it game, Box2D, Game development, HTML5, Javascript, Phaser and TypeScript.

Block it” game concept can be developed in a lot of ways, and we already saw how to build a HTML5 prototype using Phaser and Arcade Physics or using a custom continuous collision detection, getting rid of physics engines.

Now we are going to build the prototype using Box2D, which is much more complex and realistic than Arcade Physics, and in this case the drawback is Box2D is too much realistic.

If we want a ball to bounce over an edge, we need to set friction, mass, elasticity and even more properties, and there is no way to make speed increase at each contact.

Well, actually there is a way, using custom contact callbacks, which is one of the most confusing features of Box2D, along with compound objects, and in this prototype I am using them both, showing you they are quite easy to understand.

Let’s see what we are going to build:

It may seem a simple circle running inside a square, and actually it is, but the “square” is a compound object and the circle is gaining speed as it hits the square.

This wouldn’t be possible in Box2D, and some bounces where angle of ball speed is very similar to angle of the wall being it would cause the ball to roll over the ball rather than bouncing. Realistic, but not what we want.

About the compound object, it’s a normal Box2D body with more than a fixture linked to it. A body with two box fixtures will result in an object made of two boxes. I already played with compound objects in AS3 fourteen years ago then wrote a HTML5 version powered by Phaser but the best way to see then in action is on the official Planck/Box2D example. And by reading this post, of course.

About collision management, Box2D allows us to use listeners to trigger contact events, so my idea was to listen for the pre-solve event, which is fired after collision detection, but before collision resolution, and post-solve which is fired after collision resolution.

In pre-solve I am calculating the bounce angle without worrying about mass, elasticity, friction, and so on, and in post-solve I update the speed increasing it.

Let’s see the source code, made of one html file, one css file and 7 TypeScript files.

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">
        </style>
        <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;
}

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

export const GameOptions = {

    // unit used to convert pixels to meters and meters to pixels
    worldScale : 30,

    // ball radius, in pixels
    ballRadius : 25,

    // ball start speed, in meters/second
    ballStartSpeed : 2,

    // ball speed increase at each collision, in meters/second
    ballSpeedIncrease : 0.3
}

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 { PreloadAssets } from './preloadAssets';
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 : 750,
    height : 750
}

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

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

preloadAssets.ts

Here we preload all assets to be used in the game, such as the sprites used for the ball.

// CLASS TO PRELOAD ASSETS

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

    // constructor    
    constructor() {
        super({
            key : 'PreloadAssets'
        });
    }

    // method to be execute during class preloading
    preload(): void {

        // this is how we preload an image
        this.load.image('ball', 'assets/ball.png');
	}

    // method to be called once the instance has been created
	create(): void {

        // call PlayGame class
        this.scene.start('PlayGame');
	}
}

planckUtils.ts

Just a couple of functions because Box2D works with meters while Phaser and most frameworks work with pixels. Here is where we convert pixels to meters and meters to pixels.

import { GameOptions } from './gameOptions';
 
// simple function to convert pixels to meters
export function toMeters(n : number) : number {
    return n / GameOptions.worldScale;
}
 
// simple function to convert meters to pixels
export function toPixels(n: number) : number {
    return n * GameOptions.worldScale;
}

playGame.ts

Main game file, all game logic is stored here.

// THE GAME ITSELF

import * as planck from 'planck';
import { GameOptions } from './gameOptions';
import { PlanckCompound } from './planckCompound';
import { PlanckBall } from './planckBall';
import { toPixels } from './planckUtils';

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

    // Box2d world
    world : planck.World;

    // the ball
    theBall : PlanckBall;

    // planck compound object
    theCompound : PlanckCompound;

    // graphics objects to render the compound object
    compoundGraphics : Phaser.GameObjects.Graphics;

    // keep track of the number of bounces to restart the demo at 50
    bounces : number

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

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

        // zero bounces at the beginning
        this.bounces = 0

        // just a couple of variables to store game width and height
        let gameWidth : number = this.game.config.width as number;
        let gameHeight : number = this.game.config.height as number;
    
        // world gravity, as a Vec2 object. It's just a x, y vector
        let gravity = new planck.Vec2(0, 0); 
         
        // this is how we create a Box2D world
        this.world = new planck.World(gravity);

        // add the planck ball
        this.theBall = new PlanckBall(this, this.world, gameWidth / 2, gameHeight / 2, GameOptions.ballRadius, 'ball');

        // give the ball a random velocity
        this.theBall.setRandomVelocity(GameOptions.ballStartSpeed);

        // add the planck compound object
        this.theCompound = new PlanckCompound(this.world, gameWidth / 2, gameHeight / 2, 350)

        // add simulation graphics
        this.compoundGraphics = this.add.graphics();
        
        // add an event listener waiting for a contact to solve
        this.world.on('post-solve', () => {
            this.theBall.handleBounce(this.theBall.angleToReflect, GameOptions.ballSpeedIncrease);
            
            // increase number of bounces
            this.bounces ++;

            // restart the game if bounces = 50
            if (this.bounces == 50) {
                this.scene.start('PlayGame');
            }
        })

        // add an event listener waiting for a contact to pre solve
        this.world.on('pre-solve', (contact : planck.Contact) => {

            // get edge fixture in this circle Vs edge contact
            let edgeFixture : planck.Fixture = this.getEdgeFixture(contact);

            // get edge body
            let edgeBody : planck.Body = edgeFixture.getBody();

            // get edge shape
            let edgeShape : planck.Edge = edgeFixture.getShape() as planck.Edge;

            // did the ball just collided with this edge?
            if (this.theBall.sameEdgeCollision(edgeShape)) {
                
                // disable the contact
                contact.setEnabled(false);

                // exit callback function
                return;    
            }

            // get edge shape vertices
            let worldPoint1 : planck.Vec2 = edgeBody.getWorldPoint(edgeShape.m_vertex1);
            let worldPoint2 : planck.Vec2 = edgeBody.getWorldPoint(edgeShape.m_vertex2);
            
            // transform the planck edge into a Phaser line
            let worldLine : Phaser.Geom.Line = new Phaser.Geom.Line(toPixels(worldPoint1.x), toPixels(worldPoint1.y), toPixels(worldPoint2.x), toPixels(worldPoint2.y));
            
            // determine bounce angle
            this.theBall.determineBounceAngle(worldLine); 
        })
    }

    // method to get the edge fixture in a edge Vs circle contact
    getEdgeFixture(contact : planck.Contact) : planck.Fixture {

        // get first contact fixture
        let fixtureA : planck.Fixture = contact.getFixtureA(); 

        // get first contact shape
        let shapeA : planck.Shape = fixtureA.getShape();

        // is the shape an edge? Return the first contact fixture, else return second contact fixture
        return (shapeA.getType() == 'edge') ? fixtureA : contact.getFixtureB();
    }

    // method to be called at each frame
    update() : void {

        // advance the simulation by 1/30 seconds
        this.world.step(1 / 30);
  
        // crearForces  method should be added at the end on each step
        this.world.clearForces();

        // update ball position
        this.theBall.updatePosition();
        
        // draw walls of compound object
        this.theCompound.drawWalls(this.compoundGraphics);
    }
}

planckBall.ts

Custom class extending Phaser.GameObjects.Sprite to define the planck ball as a Phaser sprite.

import * as planck from 'planck';
import { toMeters, toPixels } from './planckUtils';
 
// this class extends planck Phaser Sprite class
export class PlanckBall extends Phaser.GameObjects.Sprite {

    // planck body
    planckBody : planck.Body;
    
    // ball speed
    speed : number;

    // last collided edge, to prevent colliding with the same edge twice
    lastCollidedEdge : planck.Edge;

    // angle to reflect after a collision
    angleToReflect : number;
 
    constructor(scene : Phaser.Scene, world : planck.World, posX : number, posY : number, radius : number, key : string) {
 
        super(scene, posX, posY, key);
         
        // adjust sprite display width and height
        this.displayWidth = radius * 2;
        this.displayHeight = radius * 2;
 
        // add sprite to scene
        scene.add.existing(this);
     
        // this is how we create a generic Box2D body
        this.planckBody  = world.createBody();

        // set the body as bullet for continuous collision detection
        this.planckBody.setBullet(true)
 
        // Box2D bodies are created as static bodies, but we can make them dynamic
        this.planckBody.setDynamic();
 
        // a body can have one or more fixtures. This is how we create a circle fixture inside a body
        this.planckBody.createFixture(planck.Circle(toMeters(radius)));
  
        // now we place the body in the world
        this.planckBody.setPosition(planck.Vec2(toMeters(posX), toMeters(posY)));

        // time to set mass information
        this.planckBody.setMassData({
 
            // body mass
            mass : 1,
 
            // body center
            center : planck.Vec2(),
  
            // I have to say I do not know the meaning of this "I", but if you set it to zero, bodies won't rotate
            I : 1
        });
    }

    // method to set a random velocity, given a speed
    setRandomVelocity(speed : number) : void {

        // save the speed as property
        this.speed = speed;
         
        // set a random angle
         let angle : number = Phaser.Math.Angle.Random();

         // set ball linear velocity according to angle and speed
         this.planckBody.setLinearVelocity(new planck.Vec2(this.speed * Math.cos(angle), this.speed * Math.sin(angle)))
    }

    // method to check if an edge is the one we already collided with
    sameEdgeCollision(edge : planck.Edge) : boolean {

        // check if current edge is the same as last collided edge
        let result : boolean = this.lastCollidedEdge == edge;

        // update last collided edge
        this.lastCollidedEdge = edge;

        // return the result
        return result;   
    }

    // method to handle bounce increasing speed number
    handleBounce(angle : number, speedIncrease : number) : void {

        // increase speed
        this.speed += speedIncrease;

        // set linear velocity according to angle and speed
        this.planckBody.setLinearVelocity(new planck.Vec2(this.speed * Math.cos(angle), this.speed * Math.sin(angle)));
    }

    // method to determine bounce angle against a line
    determineBounceAngle(line : Phaser.Geom.Line) : void {

        // get linear velocity
        let velocity : planck.Vec2 = this.planckBody.getLinearVelocity();

        // transform linear velocity into a line
        let ballLine : Phaser.Geom.Line = new Phaser.Geom.Line(0, 0, velocity.x, velocity.y);

        // calculate reflection angle between two lines
        this.angleToReflect = Phaser.Geom.Line.ReflectAngle(ballLine, line);   
    }

    // method to update ball position
    updatePosition() : void {
        
        // get ball planck body position
        let ballBodyPosition : planck.Vec2 = this.planckBody.getPosition();  

        // update ball position
        this.setPosition(toPixels(ballBodyPosition.x), toPixels(ballBodyPosition.y));  
    }
}

planckCompound.ts

Custom class to define the planck compound object.

import * as planck from 'planck';
import { toMeters, toPixels } from './planckUtils';
 
export class PlanckCompound {

    // planck body
    planckBody : planck.Body;
 
    constructor(world : planck.World, posX : number, posY : number, offset : number) {
 
        // this is how we create a generic Box2D body
        let compound : planck.Body = world.createKinematicBody();

        // set body position
        compound.setPosition(new planck.Vec2(toMeters(posX), toMeters(posY)))
        
        // add edge fixtures to body
        compound.createFixture(planck.Edge(new planck.Vec2(toMeters(0), toMeters(-offset)), new planck.Vec2(toMeters(offset), toMeters(0))));
        compound.createFixture(planck.Edge(new planck.Vec2(toMeters(offset), toMeters(0)), new planck.Vec2(toMeters(0), toMeters(offset))));
        compound.createFixture(planck.Edge(new planck.Vec2(toMeters(0), toMeters(offset)), new planck.Vec2(toMeters(-offset), toMeters(0))));
        compound.createFixture(planck.Edge(new planck.Vec2(toMeters(-offset), toMeters(0)), new planck.Vec2(toMeters(0), toMeters(-offset))));

        // give the compound object a random angle
        compound.setAngle(Phaser.Math.Angle.Random());

        // assign the body to planckBody property
        this.planckBody = compound;
    }

    // method to draw compount walls in a Graphics game object
    drawWalls(graphics : Phaser.GameObjects.Graphics) : void {

        // clear the graphics
        graphics.clear();

        // set line style to one pixel black
        graphics.lineStyle(1, 0x000000);

        // loop through all body fixtures
        for (let fixture : planck.Fixture = this.planckBody.getFixtureList() as planck.Fixture; fixture; fixture = fixture.getNext() as planck.Fixture) {
            
            // get fixture edge
            let edge : planck.Edge = fixture.getShape() as planck.Edge;

            // get edge vertices
            let lineStart : planck.Vec2 = this.planckBody.getWorldPoint(edge.m_vertex1);
            let lineEnd : planck.Vec2 = this.planckBody.getWorldPoint(edge.m_vertex2);
            
            // turn the planck edge into a Phaser line
            let drawLine : Phaser.Geom.Line = new Phaser.Geom.Line(
                toPixels(lineStart.x),
                toPixels(lineStart.y),
                toPixels(lineEnd.x),
                toPixels(lineEnd.y)
            );

            // stroke the line shape
            graphics.strokeLineShape(drawLine);
        }  
    }

}

And two of the most difficult Box2D concepts have been explained in a matter of minutes with a real world example. Next time I’ll turn this prototype into a more playable stuff, meanwhile download the source code.

Never miss an update! Subscribe, and I will bother you by email only when a new game or full source code comes out.