Calculating dynamic light and shadows in tile based roguelike games – part 2: drawing circles in a tile based environment

Read all posts about "" game
We are getting closer to the final algorithm to calculate dynamic light and shadow in tile based roguelike games, and we are going to cover another important feature: drawing circles in a tile based environment. While in previous step I showed you the Bresenhams line algorithm although you probably still do not know why, this time it’s quite easy to understand how we are going to use circles in a tile based environment: to simulate the radius of a point light, which could be a torch on the wall or the light halo around your character. A web page which clearly explains how to create any kind of line, circle, ellipse and Bézier curve is The Beauty of Bresenham’s Algorithm and that’s the code I translated from C to JavaScript to draw circles in a tile based environment. Look at the example:
Drag the white tiles to move both the grey line and the red circles. We are now very close to the solution of our problem and soon we will be able to create light and shadows in a tile map environment. Here is the code I used, you can save for future use drawBresenham and drawCircle functions, the other lines have just been written to make the demo work.
var game;
var gridWidth = 40;
var gridHeight = 40;
var tileSize = 16;
var sightRadius = 7;

window.onload = function() {	
	game = new Phaser.Game(640, 640, Phaser.AUTO, "");
     game.state.add("PlayGame", playGame);
     game.state.start("PlayGame");
}

var playGame = function(game){};

playGame.prototype = {
     preload: function(){
           game.load.image("tile", "tile.png");
     },
     create: function(){
          var startCol = game.rnd.between(0, gridWidth - 1);
          var startRow = game.rnd.between(0, gridHeight - 1);
          this.startPoint = game.add.sprite(startCol * tileSize, startRow * tileSize, "tile");
          this.startPoint.inputEnabled = true;
          this.startPoint.input.enableDrag();
          this.startPoint.input.boundsRect = new Phaser.Rectangle(0, 0, game.width, game.height);
          this.startPoint.input.enableSnap(tileSize, tileSize, true, true);
          do{
               var endCol = game.rnd.between(0, gridWidth - 1);
               var endRow = game.rnd.between(0, gridHeight - 1);     
          } while (startRow == endRow && startCol == endCol);
          this.endPoint = game.add.sprite(endCol * tileSize, endRow * tileSize, "tile");
          this.endPoint.inputEnabled = true;
          this.endPoint.input.enableDrag();
          this.endPoint.input.boundsRect = new Phaser.Rectangle(0, 0, game.width, game.height);
          this.endPoint.input.enableSnap(tileSize, tileSize, true, true);
          this.lineGroup = game.add.group();
     },
     update: function(){
          this.lineGroup.removeAll(true);
          this.drawBresenham(this.startPoint.x / tileSize, this.startPoint.y / tileSize, this.endPoint.x / tileSize, this.endPoint.y / tileSize);
          this.drawCircle(this.startPoint.x / tileSize, this.startPoint.y / tileSize, sightRadius);
          this.drawCircle(this.endPoint.x / tileSize, this.endPoint.y / tileSize, sightRadius);
     },
     drawBresenham: function(x0, y0, x1, y1){
          var dx = Math.abs(x1 - x0);
          var sx = -1;
          if(x0 < x1){
               var sx = 1
          }
          var dy = Math.abs(y1 - y0);
          var sy = -1;
          if(y0 < y1){
               var sy = 1;
          }
          var err = -dy / 2;
          if(dx &gt; dy){
               err = dx / 2;
          }
          do{
               var tile = game.add.sprite(x0 * tileSize, y0 * tileSize, "tile");
               tile.alpha = 0.5;
               this.lineGroup.add(tile);
               var e2 = err;
               if(e2 &gt; -dx){
                    err -= dy;
                    x0 += sx;
               }
               if(e2 < dy){
                    err += dx;
                    y0 += sy;
               }
          } while(x0 != x1 || y0 != y1)        
     },
     drawCircle: function(x0, y0, radius){
          var x = -radius
          var y = 0;
          var err = 2 - 2 * radius; 
          do {
               console.log((x0 - x) * tileSize);
               this.placeTile((x0 - x) * tileSize, (y0 + y) * tileSize, 0.5, 0xff0000);
               this.placeTile((x0 - y) * tileSize, (y0 - x) * tileSize, 0.5, 0xff0000);
               this.placeTile((x0 + x) * tileSize, (y0 - y) * tileSize, 0.5, 0xff0000);
               this.placeTile((x0 + y) * tileSize, (y0 + x) * tileSize, 0.5, 0xff0000);
               radius = err;
               if (radius <= y){
                    y++;
                    err += y * 2 + 1;
               }          
               if (radius &gt; x || err &gt; y){
                    x++;
                    err += x * 2 + 1;
               } 
          } while (x < 0);    
     },
     placeTile: function(x, y, alpha, tint){
          var tile = game.add.sprite(x, y, "tile");
          tile.tint = tint; 
          tile.alpha = alpha;
          this.lineGroup.add(tile);
     }
}
How would you turn this into a tile based game dynamic light casting? The answer in next posts, 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