Fake 3D Test
by Sam Fereday
HTML
<canvas id='display' width='1' height='1' style='width: 100%; height: 100%;'></canvas>
JavaScript
var CIRCLE = Math.PI * 2;
function Controls() {
this.codes = {
37: 'left',
39: 'right',
38: 'forward',
40: 'backward'
};
this.states = {
'left': false,
'right': false,
'forward': false,
'backward': false
};
document.addEventListener('keydown', this.onKey.bind(this, true), false);
document.addEventListener('keyup', this.onKey.bind(this, false), false);
}
Controls.prototype.onKey = function(val, e) {
var state = this.codes[e.keyCode];
if (typeof state === 'undefined') return;
this.states[state] = val;
e.preventDefault && e.preventDefault();
e.stopPropagation && e.stopPropagation();
};
function Bitmap(src, width, height) {
this.image = new Image();
this.image.src = src;
this.width = width;
this.height = height;
}
function Player(x, y, direction) {
this.x = x;
this.y = y;
this.direction = direction;
this.weapon = new Bitmap('http://demos.playfuljs.com/raycaster/assets/knife_hand.png', 319, 320);
this.paces = 0;
}
Player.prototype.rotate = function(angle) {
this.direction = (this.direction + angle + CIRCLE) % (CIRCLE);
};
Player.prototype.walk = function(distance, map) {
var dx = Math.cos(this.direction) * distance;
var dy = Math.sin(this.direction) * distance;
if (map.get(this.x + dx, this.y) <= 0) this.x += dx;
if (map.get(this.x, this.y + dy) <= 0) this.y += dy;
this.paces += distance;
};
Player.prototype.update = function(controls, map, seconds) {
if (controls.left) this.rotate(-Math.PI * seconds);
if (controls.right) this.rotate(Math.PI * seconds);
if (controls.forward) this.walk(3 * seconds, map);
if (controls.backward) this.walk(-3 * seconds, map);
};
function Map(size) {
this.size = size;
this.wallGrid = new Uint8Array(size * size);
this.skybox = new Bitmap('http://demos.playfuljs.com/raycaster/assets/deathvalley_panorama.jpg', 2000, 750);
this.wallTexture = new Bitmap('http://demos.playfuljs.com/raycaster/assets/wall_texture.jpg', 1024, 1024);
this.light...