Play with light and dark using ray casting and visibility polygons

If you are a long time reader, you should already know about my survival horror game prototypes, the latest of them was Phaser tutorial: how to create an HTML5 survival horror game in 6 easy steps.

Although the way to determine light and dark works pretty well, it leaves room for improvement, and such improvement comes from ray casting.

From Wikipedia: « Ray casting is the use of ray-surface intersection tests to solve a variety of problems in computer graphics and computational geometry. The term was first used in computer graphics in a 1982 paper by Scott Roth to describe a method for rendering constructive solid geometry models. »

The concept is simple: starting from the “eye” of the player, we cast a series of rays and for each ray we find the first segment the ray hits. We can say there is light until the ray travels free, and dark once the ray is stopped by a segment.

My survival horror prototype used a poor ray casting method since it only fired a series of rays here and there – every n degrees – checking for collisions with a bitmap object.

A realistic survival horror would cast rays in a smarter way, such as only casting them through polygons vertices, and building the light polygon out of them.

To tell the truth, is not that easy, and since there’s no need to reinvent the wheel, I am using Byron Knoll‘s visibility polygon script, applied to a Phaser script to render the results.

This is what you will get:

Move the mouse around the stage to see the light polygon.

The source code, thanks to visibility polygon script, is very easy:

window.onload = function() {
	
	var game = new Phaser.Game(640, 480, Phaser.CANVAS, "", {create: onCreate});                

	// the canvas where we will show the obstaclesCanvas
	var obstaclesCanvas;
	// the canvas where we will show the light
	var lightCanvas; 
	// number of boxes on the stage
	var numBoxes = 5;
	// array which will store all polygons
	var polygons = [];
	
	function onCreate() {
		// listener to mouse movement		
          moveIndex = game.input.addMoveCallback(move, this);
		// the canvas where we will show the obstaclesCanvas
		obstaclesCanvas = game.add.graphics(0,0); 
		// line style of obstacle canvas
		obstaclesCanvas.lineStyle(4, 0xffffff, 1);
          // the canvas where we will display the scene
		lightCanvas = game.add.graphics(0,0);
		// placing some ramdom boxes
          for(var i = 0; i < numBoxes; i++){
			randomBox();	
		}
		// placing the perimeter box
		polygons.push([[-1,-1],[game.width+1,-1],[game.width+1,game.height+1],[-1,game.height+1]]);			
	}
	
	function randomBox(){
		do{
			// drawing boxes with random width, height and upper corner coordinates
			var width = game.rnd.between(50,150);
			var height = game.rnd.between(50,150);
			var startX = game.rnd.between(10,game.width-160);
			var startY = game.rnd.between(10,game.height-160);
		}while(boxesIntersect(startX,startY,width,height))
		// drawing the boxes
		obstaclesCanvas.drawRect(startX, startY, width, height);
		// pushing the newly created box into polygons array
		polygons.push([[startX,startY],[startX+width,startY],[startX+width,startY+height],[startX,startY+height]]);		
	}
	
	// this is just a function to prevent boxes to insersect or the library won't work
	function boxesIntersect(x,y,w,h){  
		for(var i = 0; i < polygons.length; i++){
			if(x<polygons[i][1][0] && x+w>polygons[i][0][0] && y<polygons[i][3][1] && y+h>polygons[i][0][1]){
				return true;
			}
		}
		return false;
	}
          
     function move(){ 
		// when the mouse is moved, we determine the new visibility polygon 	
     	var visibility = createLightPolygon(game.input.worldX, game.input.worldY);
     	// then we draw it
		lightCanvas.clear();
		lightCanvas.lineStyle(2, 0xff8800, 1);
		lightCanvas.beginFill(0xffff00); 
		lightCanvas.moveTo(visibility[0][0],visibility[0][1]);	
     	for(var i=1;i<=visibility.length;i++){
			lightCanvas.lineTo(visibility[i%visibility.length][0],visibility[i%visibility.length][1]);		
		}
		lightCanvas.endFill();
	}
	
	// and this is how the library generates the visibility polygon starting
	// from an array of polygons and a source point
	function createLightPolygon(x,y){
		var segments = VisibilityPolygon.convertToSegments(polygons);
		segments = VisibilityPolygon.breakIntersections(segments);
		var position = [x, y];
		if (VisibilityPolygon.inPolygon(position, polygons[polygons.length-1])) {
  			return VisibilityPolygon.compute(position, segments);
		}      
		return null;
	}	
}

This should improve a lot your light and dark survival horror games. I will publish some examples next days, meanwhile you can download the full source code with all required libraries.

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