“VVVVVV” HTML5 prototype powered by Phaser meets light and dark with ray casting and the result is astonishing

Read all posts about "" game

Sometimes, you don’t have to squeeze your brain to find an original gameplay.

Sometimes, it’s just a matter of combining two existing gameplays and see what happens.

So I combined my HTML5 VVVVVV prototype with the ray casting light and dark generator, and the result is really interesting, but before you start using it in your actual games, I have to warn you: we positively MUST find a way to reduce the number of polygons.

In this prototype, each tile of the level, built with Tiled Map Editor, has been converted in a polygon, but this is a very unoptimized way to create the environment.

We should be able to reduce the amount of polygons by grouping adjacent squares into bigger rectangles.

Anyway, this is what we have at the moment:

Move left and right with LEFT and RIGHT arrow keys, switch gravity with SPACEBAR, but once you switch the gravity, you’ll have to wait for the character to land on the ground – or on the ceiling – to be able to switch gravity once more.

Press/release W to show or hide walls. As you can see, there are too much walls.

Ray casting algorithm is powered by Byron Knoll‘s visibility polygon.

And here is the source code:

let game;
let gameOptions = {
    playerGravity: 1200,
    playerSpeed: 200
}
window.onload = function() {
    var gameConfig = {
        type: Phaser.AUTO,
        backgroundColor: 0x000000,
        scale: {
            mode: Phaser.Scale.FIT,
            autoCenter: Phaser.Scale.CENTER_BOTH,
            parent: "thegame",
            width: 640,
            height: 480
        },
        physics: {
            default: "arcade",
            arcade: {
                gravity: {
                    y: 0
                }
            }
        },
        scene: playGame
    }
    game = new Phaser.Game(gameConfig);
}
class playGame extends Phaser.Scene{
    constructor(){
        super("PlayGame");
    }
    preload(){
        this.load.tilemapTiledJSON("level", "level.json");
        this.load.image("tile", "tile.png");
        this.load.image("hero", "hero.png");
    }
    create(){
        this.gravityDirection = 1;
        this.map = this.make.tilemap({
            key: "level"
        });
        let tile = this.map.addTilesetImage("tileset01", "tile");
        this.map.setCollision(1);
        this.layer = this.map.createStaticLayer("layer01", tile);
        let polygons = [];
        this.layer.forEachTile(function(t){
            if(t.index == 1){
                polygons.push([[t.pixelX, t.pixelY], [t.pixelX + t.width, t.pixelY], [t.pixelX + t.width, t.pixelY + t.height], [t.pixelX, t.pixelY + t.height]]);
            }
        }.bind(this));
        polygons.push([[-1, -1], [this.layer.width + 1 , - 1], [this.layer.width + 1, this.layer.height + 1], [-1, this.layer.height + 1]]);
        this.canFlipGravity = true;
        this.cursors = this.input.keyboard.createCursorKeys();
        let spaceKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);
        spaceKey.on("down", function(){
            if(this.canFlipGravity){
                this.hero.body.gravity.y *= -1;
                this.canFlipGravity = false;
                this.hero.flipY = this.hero.body.gravity.y < 0
            }
        }, this);
        let wKey = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.W);
        wKey.on("down", function(){
            this.wallGraphics.setVisible(true);
        }, this);
        wKey.on("up", function(){
            this.wallGraphics.setVisible(false);
        }, this);
		this.wallGraphics = this.add.graphics();
        this.wallGraphics.setVisible(false);
		this.wallGraphics.lineStyle(1, 0x00ff00);
		this.lightGraphics = this.add.graphics();
        polygons.forEach(function(p){
            this.wallGraphics.strokeRect(p[0][0], p[0][1], p[2][0] - p[0][0],  p[2][1] - p[0][1]);
        }.bind(this));
        this.hero = this.physics.add.sprite(300, 376, "hero");
        this.hero.body.gravity.y = gameOptions.playerGravity;
        this.cameras.main.setBounds(0, 0, 1920, 1440);
        this.cameras.main.startFollow(this.hero);
        this.segments = VisibilityPolygon.convertToSegments(polygons);
		this.segments = VisibilityPolygon.breakIntersections(this.segments);
    }
    update(){
        this.drawLightPolygon();
        this.hero.body.velocity.y = Phaser.Math.Clamp(this.hero.body.velocity.y, -800, 800);
        this.hero.body.velocity.x = this.cursors.left.isDown ? (this.cursors.right.isDown ? 0 : -1 * gameOptions.playerSpeed) : (this.cursors.right.isDown ? gameOptions.playerSpeed : 0);
        this.hero.flipX = this.hero.body.velocity.x == 0 ? this.hero.flipX : (this.hero.body.velocity.x > 0 ? false : true);
        this.physics.world.collide(this.hero, this.layer, function(hero, layer){
            if(hero.body.blocked.down || hero.body.blocked.up){
                this.canFlipGravity = true;
            }
        }, null, this);
    }
    drawLightPolygon(){
		let position = [this.hero.x, this.hero.y];
		let light = VisibilityPolygon.compute(position, this.segments);
		this.lightGraphics.clear();
		this.lightGraphics.lineStyle(2, 0xff8800);
		this.lightGraphics.fillStyle(0xffff00);
		this.lightGraphics.beginPath();
        this.lightGraphics.moveTo(light[0][0], light[0][1]);
        for(let i = 1; i <= light.length; i ++){
            this.lightGraphics.lineTo(light[i % light.length][0], light[ i % light.length][1]);
        }
		this.lightGraphics.closePath();
    	this.lightGraphics.fillPath();
    	this.lightGraphics.strokePath();
	}
}

I am really proud of this experiment, and once I find a decent way to reduce the amount of polygons, I’ll update and comment the script, 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