Pixel based physics engine with HTML5 example powered by Phaser

Here I am with a pixel based physics engine. What is a pixel based physics engine? It’s basically a physics engine without physics: there is just a bouncing ball whose circumference is constantly scanned to check if overlaps some stuff on the screen. Then we use trigonometry to calcolate how should the ball bounce.

Due to the inefficient way to handle physics, the simulation is not accurate and I doubt you will be able to build something more interesting than a bouncing ball, but on the other hand you don’t need any physics engine as long as you have some way to check for pixels alpha.

Then years ago I was able to use this engine to create LineBall game, sponsored by both Coolbuddy and Armor Games, so why not giving it a try? Here is an example of what the engine is capable of:

Just look how the ball jumps on a randomly generated terrain.

It might not be the most realistic physics simulation, but it’s more than adequate for a quick game.

And the interesting thing is the engine itself is about 40 lines long, almost with no dependencies: I just needed to use getPixelAlpa Phaser method to check for pixels alpha, but the whole engine, all inside update method, is pure JavaScript.

Have a look at the source code:

let game
let gameOptions = {
    ballRadius: 10,
    gravity: 0.05,
    maxSpeed: 10,
    precision: 120,
    friction: 0.9
}
window.onload = function() {
    var gameConfig = {
        type: Phaser.AUTO,
        backgroundColor: 0xf5f5f5,
        scale: {
            mode: Phaser.Scale.FIT,
            autoCenter: Phaser.Scale.CENTER_BOTH,
            parent: "thegame",
            width: 640,
            height: 480
        },
        scene: playGame
    }
    game = new Phaser.Game(gameConfig);
}
class playGame extends Phaser.Scene{
    constructor(){
        super("PlayGame");
    }
    create(){
        this.ball = this.add.graphics();
        this.ball.fillStyle(0xFf0000, 1);
        this.ball.fillCircle(0, 0, gameOptions.ballRadius);
        this.ball.x = game.config.width / 2;
        this.ball.y = 0;
        this.speed = new Phaser.Math.Vector2(0, 0);
        let graphics = this.add.graphics();
        for(let i = 0; i < 5; i++){
            let angle = Phaser.Math.RND.rotation();
            let originX = Phaser.Math.RND.integerInRange(100, game.config.width - 100);
            let originY = Phaser.Math.RND.integerInRange(100, game.config.height - 100);
            let width = Phaser.Math.RND.integerInRange(120, 240);
            let triangle = Phaser.Geom.Triangle.BuildEquilateral(originX, originY, width);
            Phaser.Geom.Triangle.Rotate(triangle, angle);
            graphics.fillStyle(0x444444, 1);
            graphics.beginPath();
            graphics.moveTo(triangle.x1, triangle.y1);
            graphics.lineTo(triangle.x2, triangle.y2);
            graphics.lineTo(triangle.x3, triangle.y3);
            graphics.closePath();
            graphics.fillPath();
        }
        graphics.generateTexture("texture", game.config.width, game.config.height);
        graphics.clear();
        this.ground = this.add.sprite(game.config.width / 2, game.config.height / 2, "texture");
        let timedEvent = this.time.addEvent({
            delay: 10000,
            callback: function(){
                location.reload();
            }
        });
    }
    update(){
        this.ball.x = Phaser.Math.Wrap(this.ball.x, 0, game.config.width);
        this.ball.y = Phaser.Math.Wrap(this.ball.y, 0, game.config.height);
        let collisions = 0;
        let sumCollisionX = 0;
        let sumCollisionY = 0;
        this.ball.x += this.speed.x;
        this.ball.y += this.speed.y;
        this.speed.y += gameOptions.gravity;
        this.speed.x = Phaser.Math.Clamp(this.speed.x, -gameOptions.maxSpeed, gameOptions.maxSpeed);
        this.speed.y = Phaser.Math.Clamp(this.speed.y, -gameOptions.maxSpeed, gameOptions.maxSpeed)
        for(let i = 1; i <= gameOptions.precision; i++){
            let testX = this.ball.x + gameOptions.ballRadius * Math.sin(i * 2 * Math.PI / gameOptions.precision);
			let testY = this.ball.y + gameOptions.ballRadius * Math.cos(i * 2 * Math.PI / gameOptions.precision);
            let alpha = this.textures.getPixelAlpha(testX, testY, "texture");
            if(alpha > 0){
                collisions ++;
                sumCollisionX += testX;
                sumCollisionY += testY;
            }
        }
        let averageX = sumCollisionX / collisions;
        let averageY = sumCollisionY / collisions;
        if(collisions > 0){
            let collisionAngle = Math.atan2(this.ball.y - averageY, this.ball.x - averageX);
            let collisionX = this.ball.x - gameOptions.ballRadius * Math.cos(collisionAngle);
            let collisionY = this.ball.y - gameOptions.ballRadius * Math.sin(collisionAngle);
            let deltaX = (collisionX - this.ball.x) / gameOptions.ballRadius;
            let deltaY = (collisionY - this.ball.y) / gameOptions.ballRadius;
            let speed = Math.sqrt(this.speed.x * this.speed.x + this.speed.y * this.speed.y) * gameOptions.friction;
            let direction = Math.atan2(this.speed.y, this.speed.x);
            let bounceAngle = 2 * collisionAngle - direction + Math.PI;
            this.speed.x = Math.cos(bounceAngle) * speed;
            this.speed.y = Math.sin(bounceAngle) * speed;
            while(this.textures.getPixelAlpha(collisionX, collisionY, "texture")){
                this.ball.x += 0.1 * Math.cos(bounceAngle);
                this.ball.y += 0.1 * Math.sin(bounceAngle);
                collisionX = this.ball.x - gameOptions.ballRadius * Math.cos(collisionAngle);
                collisionY = this.ball.y - gameOptions.ballRadius * Math.sin(collisionAngle);
			}
		}
    }
}

Do you find this useful? Or do you prefer more robust and complex engines for your games, even if they only feature a bouncing ball? Download the source code of the project and experiment with it.

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
// Mini Archer
// 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
// 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