Build a HTML5 game like “Ballz” using Phaser and ARCADE physics

Read all posts about "" game
We are going to start the new year with a new tutorial series, this time we’ll see how to create a HTML5 version of Ballz by Ketchapp Studio. It’s an interesting take to the brick breaker genre, with easy and intuitive controls as you should expect from any mobile game. Before we start coding, let’s have a look at the game area: We are going to use ARCADE physics to handle the game. We don’t need any complex engine like Box2D because this game does not feature friction, gravity, or realistic collision detection, so we are using the simplest physics engine Phaser provides. In this first part, we are going to create the game field, the ball, the fake predictive trajectory and the player interaction as well as the physics involved in launching the ball. Have a look at the result:
Tap/click and drag to the bottom to aim the ball, release to launch it. If you have a mobile device, you can play it directly from this link. And this is the completely commented source code, the entire prototype was made in 80 lines of code, which is quite awesome:
// the game itself
var game;

// global options
var gameOptions = {

    // score panel height / game height
    scorePanelHeight: 0.08,

    // launch panel height / game height
    launchPanelHeight: 0.18,

    // ball size / game width
    ballSize: 0.04,

    // ball speed, in pixels/second
    ballSpeed: 1000
}

// when the window loads...
window.onload = function() {

    // game creation
    game = new Phaser.Game(640, 960, Phaser.CANVAS);

    // add "PlayGame" state and execute it
    game.state.add("PlayGame", playGame, true);
}

// "PlayGame" state
var playGame = function(){}
playGame.prototype = {

    // when the state preloads
	preload: function(){

        // load graphic assets
        game.load.image("ball", "ball.png");
        game.load.image("panel", "panel.png");
        game.load.image("trajectory", "trajectory.png");
	},

    // once the state has been created
    create: function(){

        // scale and background settings
        game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
        game.scale.pageAlignHorizontally = true;
        game.scale.pageAlignVertically = true;
        game.stage.backgroundColor = 0x202020;

        // start ARCADE physics system
        game.physics.startSystem(Phaser.Physics.ARCADE);

        // place score panel
        var scorePanel = game.add.image(0, 0, "panel");
        scorePanel.width = game.width;
        scorePanel.height = Math.round(game.height * gameOptions.scorePanelHeight);

        // place launch panel
        this.launchPanel = game.add.sprite(0, game.height, "panel");
        this.launchPanel.width = game.width;
        this.launchPanel.height = Math.round(game.height * gameOptions.launchPanelHeight);
        this.launchPanel.anchor.set(0, 1);

        // enable ARCADE physics on launch panel
        game.physics.enable(this.launchPanel, Phaser.Physics.ARCADE);

        // launch panel will not move
        this.launchPanel.body.immovable = true;

        // place the ball
        var ballSize = game.width * gameOptions.ballSize;
        this.ball = game.add.sprite(game.width / 2, game.height - this.launchPanel.height - ballSize / 2, "ball");
        this.ball.width = ballSize;
        this.ball.height = ballSize;
        this.ball.anchor.set(0.5);

        // enable ARCADE physics on the ball
        game.physics.enable(this.ball, Phaser.Physics.ARCADE);

        // the ball will collide on bounds
        this.ball.body.collideWorldBounds=true;
        this.ball.body.bounce.set(1);

        // place the trajectory
        this.trajectory = game.add.sprite(this.ball.x, this.ball.y, "trajectory");
        this.trajectory.anchor.set(0.5, 1);
        this.trajectory.visible = false;

        // wait for player input
        game.input.onDown.add(this.aimBall, this);
        game.input.onUp.add(this.shootBall, this);
        game.input.addMoveCallback(this.adjustBall, this);

        // the player is not aiming
        this.aiming = false;

        // the player is not shooting
        this.shooting = false;
	},

    aimBall: function(e){

        // if the player is not shooting...
        if(!this.shooting){

            // the player is aiming
            this.aiming = true;
        }
    },

    adjustBall: function(e){

        // if the player is aiming...
        if(this.aiming){

            // check distance between initial and current input  position
            var distX = e.position.x - e.positionDown.x;
            var distY = e.position.y - e.positionDown.y;

            // a vertical distance of at least 10 pixels is required
            if(distY > 10){

                // place the trajectory over the ball
                this.trajectory.position.set(this.ball.x, this.ball.y);

                // show trajectory
                this.trajectory.visible = true;

                // calculate direction
                this.direction = Phaser.Math.angleBetween(e.position.x, e.position.y, e.positionDown.x, e.positionDown.y);

                // adjust trajectory angle according to direction, in degrees
                this.trajectory.angle = Phaser.Math.radToDeg(this.direction) + 90;
            }
            else{

                // hide trajectory
                this.trajectory.visible = false;
            }
        }
    },

    shootBall: function(){

        // if the trajectory is visible...
        if(this.trajectory.visible){

            // get angle of fire in radians
            var angleOfFire = Phaser.Math.degToRad(this.trajectory.angle - 90);

            // set ball velocity
            this.ball.body.velocity.set(gameOptions.ballSpeed * Math.cos(angleOfFire), gameOptions.ballSpeed * Math.sin(angleOfFire));

            // the player is shooting!
            this.shooting = true;
        }

        // do not aim anymore
        this.aiming = false;

        // do not show the trajectory anymore
        this.trajectory.visible = false;
    },

    update: function(){

        // if the player is shooting...
        if(this.shooting){

            // check for collision between the ball and the launch panel
            game.physics.arcade.collide(this.ball, this.launchPanel, function(){

                // stop the ball
                this.ball.body.velocity.set(0);

                // the player is not shooting
                this.shooting = false;
            }, null, this);
        }
    }
}
In next step we’ll add targets and multiball, 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