var World = { size: 32, level: null, loadLevel: function(index) { this.level = Levels[index]; Player.x = this.level.spawnX * this.size + this.size/2; Player.y = this.level.spawnY * this.size + this.size/2; }, drawWorld2D: function() { for(var x = 0; x < this.level.width; x++) { for(var y = 0; y < this.level.height; y++) { cell = this.level.tiles[x + (y * this.level.width)]; var color = Tiles.findByID(cell).Color; Canvas.drawRect(x * this.size, y * this.size, this.size, this.size, "rgb(" + color.R + "," + color.G + "," + color.B + ")"); } } Player.draw(); }, rayCast: function(x, y, radian) { var maxDist = (this.level.width + this.level.height); var hrayX, hrayY, hoffX, hoffY, distDone, hmapX, hmapY, htileHit; var hDir = "north"; distDone = 0; //horizontal var aTan = -1/Math.tan(radian); if(radian > Math.PI) { hrayY = (Math.floor(y / this.size) * this.size) - 0.01; hrayX = (y - hrayY) * aTan + x; hoffY = -this.size; hoffX = -hoffY*aTan; } else if(radian < Math.PI) { hrayY = (Math.floor(y / this.size) * this.size) + this.size; hrayX = (y - hrayY) * aTan + x; hoffY = this.size; hoffX = -hoffY*aTan; hDir = "south"; } else { hrayX = x; hrayY = y; distDone = maxDist; } while (distDone < maxDist) { hmapX = Math.floor(hrayX / this.size); hmapY = Math.floor(hrayY / this.size); var htileHitId = this.level.tiles[hmapX + hmapY * this.level.width]; htileHit = Tiles.findByID(htileHitId); if(htileHit && htileHit.Solid) { distDone = maxDist; } else { hrayX += hoffX; hrayY += hoffY; distDone += 1; } } var hResult = { tile: htileHit, endX: hrayX, endY: hrayY, dir: hDir } //vertical var rayX, rayY, offX, offY, distDone, mapX, mapY, tileHit; var vDir = "east"; var nTan = -Math.tan(radian); distDone = 0; if(radian > Math.PI / 2 && radian < Math.PI * 1.5) { rayX = (Math.floor(x / this.size) * this.size) - 0.01; rayY = (x - rayX) * nTan + y; offX = -this.size; offY = -offX*nTan; } else if(radian < Math.PI / 2 || radian > Math.PI * 1.5) { rayX = (Math.floor(x / this.size) * this.size) + this.size; rayY = (x - rayX) * nTan + y; offX = this.size; offY = -offX*nTan; vDir = "west"; } else { rayX = x; rayY = y; distDone = maxDist; } while (distDone < maxDist) { mapX = Math.floor(rayX / this.size); mapY = Math.floor(rayY / this.size); var tileHitId = this.level.tiles[mapX + mapY * this.level.width]; tileHit = Tiles.findByID(tileHitId); if(tileHit && tileHit.Solid) { distDone = maxDist; } else { rayX += offX; rayY += offY; distDone += 1; } } var vResult = { tile: tileHit, endX: rayX, endY: rayY, dir: vDir } var vectorH = new Vector(hResult.endX - x, hResult.endY - y); var vectorV = new Vector(vResult.endX - x, vResult.endY - y); hResult.distance = vectorH.length(); vResult.distance = vectorV.length(); if(vectorH.length() < vectorV.length()) return hResult; else return vResult; } }