Raycasting - 2D Visibility
Quick implementation of a 2D visibility system. Not yet optimized.
HTML
<canvas id="displayCanvas">
Your browser doesn't support HTML5.
</canvas>
CSS
html, body{
margin: 0px;
padding: 0px;
}
body{
background-color: whitesmoke;
}
#displayCanvas{
border: 1px solid black;
}
JavaScript
var canvas = null;
var context = null;
var canvasWidth = 800;
var canvasHeight = 600;
window.onload = function(){
canvas = document.getElementById("displayCanvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
context = canvas.getContext("2d");
var game = new Game(canvas, context);
// Add the canvas boundaries as walls
game.walls.push(new Wall(new Point(0, 0), new Point(0, canvas.height)));
game.walls.push(new Wall(new Point(0, canvas.height), new Point(canvas.width, canvas.height)));
game.walls.push(new Wall(new Point(canvas.width, canvas.height), new Point(canvas.width, 0)));
game.walls.push(new Wall(new Point(canvas.width, 0), new Point(0, 0)))
// Add additional walls
game.walls.push(new Wall(new Point(100, 100), new Point(200, 100)));
game.walls.push(new Wall(new Point(500, 300), new Point(600, 423)));
game.walls.push(new Wall(new Point(400, 250), new Point(400, 500)));
game.start();
}
function Game(canvas, context){
this.canvas = canvas;
this.context = context;
this.inputManager = new InputManager(this);
this.inputManager.init();
this.clearColor = "#FFFFFF";
this.walls = [];
this.hitpoints = [];
}
Game.prototype.start = function(){
this.update();
this.render();
window.requestAnimationFrame(this.start.bind(this));
}
Game.prototype.clear = function(){
this.context.save();
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.context.fillStyle = this.clearColor;
this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.context.restore();
}
Game.prototype.update = function(){
var mouseX = this.inputManager.mouseX;
var mouseY = this.inputManager.mouseY;
this.hitpoints = [];
// For every wall...
for(var i = 0; i < this.walls.length; i++){
var wall = this.walls[i];
// Cast a ray to every point of the current wall
for(var j = 0; j < wall.points.length; j++){
var closestPoint = null;
if(j == 0) closestPoint = wall.p1;
if(j == 1) closestPoint = wall.p2;
var ray =...