Calculating dynamic light and shadows in tile based roguelike games – part 1: Bresenham’s line algorithm
Talking about Roguelike game, Game development, HTML5, Javascript and Phaser.
Learn cross platform HTML5 game development
Check my Gumroad page for commented source code, games and books.
var game;
var gridWidth = 40;
var gridHeight = 40;
var tileSize = 16;
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();
this.lineGraphics = game.add.graphics(0, 0);
},
update: function(){
this.lineGroup.removeAll(true);
this.lineGraphics.clear();
this.lineGraphics.lineStyle(3, 0x00ff00);
this.lineGraphics.moveTo(this.startPoint.x + tileSize / 2, this.startPoint.y + tileSize / 2);
this.lineGraphics.lineTo(this.endPoint.x + tileSize / 2, this.endPoint.y + tileSize / 2);
var x0 = this.startPoint.x / tileSize;
var x1 = this.endPoint.x / tileSize;
var y0 = this.startPoint.y / tileSize;
var y1 = this.endPoint.y / tileSize;
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 > 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 > -dx){
err -= dy;
x0 += sx;
}
if(e2 < dy){
err += dx;
y0 += sy;
}
} while(x0 != x1 || y0 != y1)
}
}
Never miss an update! Subscribe, and I will bother you by email only when a new game or full source code comes out.