In HTML canvas, make a 3D maze game using Raycasting
- User
In HTML canvas, make a 3D maze game using Raycasting
- Assistant
In HTML canvas, make a 3D maze game using Raycasting
Sure! Here's a simple 3D maze game implemented using raycasting in an HTML canvas. The code includes comments to help you understand how it works.
index.html):<!DOCTYPE html>
<html>
<head>
<title>3D Maze Game with Raycasting</title>
<style>
body { margin: 0; }
canvas { display: block; background-color: #000; }
</style>
</head>
<body>
<canvas id="gameCanvas"></canvas>
<script src="game.js"></script>
</body>
</html>
game.js):// Get the canvas element and set up the context
const canvas = document.getElementById('gameCanvas');
const context = canvas.getContext('2d');
// Resize the canvas to fill the window
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
// Define the 2D map of the maze
const map = [
[1,1,1,1,1,1,1,1],
[1,0,0,0,0,0,0,1],
[1,0,1,0,0,0,0,1],
[1,0,1,0,1,1,0,1],
[1,0,0,0,0,0,0,1],
[1,1,1,1,1,1,1,1]
];
// Player object to hold position and direction
let player = {
x: 2, // Player's X position in the map
y: 2, // Player's Y position in the map
angle: 0 // Direction the player is facing (in radians)
};
// Game settings
const fov = Math.PI / 3; // Field of view (60 degrees)
const numRays = canvas.width / 2; // Number of rays to cast (one per column)
const maxDepth = 20; // Maximum depth the rays can travel
// Keyboard input handling
let keys = {};
window.addEventListener('keydown', function(e) {
keys[e.key] = true;
});
window.addEventListener('keyup', function(e) {
keys[e.key] = false;
});
// The main game loop
function gameLoop() {
update();
render();
requestAnimationFrame(gameLoop);
}
// Update the game state (handle player movement)
function update() {
const moveSpeed = 0.05;
const rotSpeed = 0.03;
if (keys['ArrowUp'] || keys['w']) {
// Move forward
const newX = player.x + Math.cos(player.angle) * moveSpeed;
const newY = player.y + Math.sin(player.angle) * moveSpeed;
if (map[Math.floor(newY)][Math.floor(newX)] === 0) {
player.x = newX;
player.y = newY;
}
}
if (keys['ArrowDown'] || keys['s']) {
// Move backward
const newX = player.x - Math.cos(player.angle) * moveSpeed;
const newY = player.y - Math.sin(player.angle) * moveSpeed;
if (map[Math.floor(newY)][Math.floor(newX)] === 0) {
player.x = newX;
player.y = newY;
}
}
if (keys['ArrowLeft'] || keys['a']) {
// Rotate left
player.angle -= rotSpeed;
}
if (keys['ArrowRight'] || keys['d']) {
// Rotate right
player.angle += rotSpeed;
}
// Keep the angle between 0 and 2PI
player.angle %= Math.PI * 2;
if (player.angle < 0) {
player.angle += Math.PI * 2;
}
}
// Render the scene
function render() {
context.clearRect(0, 0, canvas.width, canvas.height);
renderScene(); // Render the 3D view
renderMinimap(5); // Render the minimap (scale factor of 5)
}
// Render the 3D scene using raycasting
function renderScene() {
for (let i = 0; i < numRays; i++) {
// Calculate the angle of the current ray
let rayAngle = (player.angle - fov / 2) + (i / numRays) * fov;
rayAngle %= Math.PI * 2;
if (rayAngle < 0) {
rayAngle += Math.PI * 2;
}
// Perform raycasting to find distance to the wall
let distanceToWall = castRay(rayAngle);
// Correct the fish-eye effect
distanceToWall *= Math.cos(player.angle - rayAngle);
// Calculate the height of the wall slice to draw
const wallHeight = Math.min(canvas.height, (canvas.height / distanceToWall));
// Calculate the color shade based on distance
const shade = Math.max(0, 255 - distanceToWall * 15);
context.fillStyle = `rgb(${shade}, ${shade}, ${shade})`;
// Draw the wall slice
context.fillRect(
i * (canvas.width / numRays), // X position
(canvas.height / 2) - (wallHeight / 2), // Y position
(canvas.width / numRays) + 1, // Width of the slice
wallHeight // Height of the slice
);
}
}
// Cast a single ray and return the distance to the wall
function castRay(angle) {
const sin = Math.sin(angle);
const cos = Math.cos(angle);
let distance = 0.0;
let hit = false;
while (!hit && distance < maxDepth) {
distance += 0.01;
const x = player.x + cos * distance;
const y = player.y + sin * distance;
const mapX = Math.floor(x);
const mapY = Math.floor(y);
// Check if the ray is out of bounds
if (mapY < 0 || mapY >= map.length || mapX < 0 || mapX >= map[0].length) {
hit = true;
distance = maxDepth;
} else if (map[mapY][mapX] > 0) {
// Ray hits a wall
hit = true;
}
}
return distance;
}
// Render a minimap in the corner of the screen
function renderMinimap(scale) {
const cellSize = 10 * scale;
for (let y = 0; y < map.length; y++) {
for (let x = 0; x < map[y].length; x++) {
if (map[y][x] > 0) {
context.fillStyle = 'gray';
} else {
context.fillStyle = 'white';
}
context.fillRect(x * cellSize, y * cellSize, cellSize, cellSize);
}
}
// Draw the player on the minimap
context.fillStyle = 'red';
context.fillRect(player.x * cellSize - 2, player.y * cellSize - 2, 4, 4);
// Draw the player's facing direction
const dirX = player.x + Math.cos(player.angle) * 0.5;
const dirY = player.y + Math.sin(player.angle) * 0.5;
context.beginPath();
context.moveTo(player.x * cellSize, player.y * cellSize);
context.lineTo(dirX * cellSize * scale, dirY * cellSize * scale);
context.strokeStyle = 'red';
context.stroke();
}
// Start the game loop
gameLoop();
Canvas Setup: The canvas is resized to fill the entire browser window, and it automatically adjusts when the window is resized.
Map Data: The maze is represented as a 2D array (map) where 1 represents walls and 0 represents open space.
Player Object: The player's position (x, y) and facing direction (angle) are stored in the player object.
Raycasting: The renderScene function casts rays within the player's field of view. For each ray, it calculates the distance to the nearest wall by incrementally moving along the ray and checking for wall collisions in the castRay function.
Rendering the Scene: Each wall slice is drawn as a vertical rectangle (fillRect) whose height is inversely proportional to the distance to the wall, creating a pseudo-3D effect.
Movement and Rotation: The update function handles player movement and rotation based on keyboard input. Collision detection prevents the player from walking through walls.
Minimap: The renderMinimap function draws a small overhead view of the maze in the corner of the screen, showing the player's position and direction.
W or Up ArrowS or Down ArrowA or Left ArrowD or Right ArrowWith this code, you should have a functional 3D maze game using raycasting in an HTML canvas. You can customize the map array to create different maze layouts. Feel free to expand upon this code by adding textures, more complex maps, or additional features like game objectives and enemy characters.
Feel free to ask if you have any questions or need further assistance!
Not yet included in a published release.