Write javascript and html code: a doom-style game
- User
Write javascript and html code: a doom-style game
- Assistant
Creating a full-fledged Doom-style game from scratch using JavaScript and HTML is a significant undertaking. However, I can provide you with a simplified version that demonstrates the core concepts of a raycasting engine, similar to the one used in early 3D games like Doom and Wolfenstein 3D.
Below is the code for a basic raycasting engine written in JavaScript and HTML. This example will render a simple 3D environment where you can move around using the arrow keys.
HTML Code (
index.html):<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Simple Raycasting Demo</title> <style> body { margin: 0; overflow: hidden; background-color: #000; } canvas { display: block; } </style> </head> <body> <canvas id="gameCanvas" width="800" height="600"></canvas> <script src="game.js"></script> </body> </html>JavaScript Code (
game.js):// Get the canvas and context const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); // Map configuration: 0 = empty space, 1 = wall const map = [ [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,1,1,1,1,0,0,0,0,0,1], [1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1], [1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1], [1,0,0,0,0,0,1,1,1,1,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] ]; const mapWidth = map[0].length; const mapHeight = map.length; // Player's starting position and direction let posX = 3.5; let posY = 5; let dirX = -1; let dirY = 0; let planeX = 0; let planeY = 0.66; // FOV (field of view) factor // Movement variables const moveSpeed = 0.05; const rotSpeed = 0.03; // Key state const keys = {}; // Event listeners for key presses document.addEventListener('keydown', (e) => { keys[e.key] = true; }); document.addEventListener('keyup', (e) => { keys[e.key] = false; }); // Game loop function gameLoop() { update(); render(); requestAnimationFrame(gameLoop); } // Update function function update() { // Move forward if (keys['ArrowUp'] || keys['w']) { if (map[Math.floor(posY)][Math.floor(posX + dirX * moveSpeed)] === 0) posX += dirX * moveSpeed; if (map[Math.floor(posY + dirY * moveSpeed)][Math.floor(posX)] === 0) posY += dirY * moveSpeed; } // Move backward if (keys['ArrowDown'] || keys['s']) { if (map[Math.floor(posY)][Math.floor(posX - dirX * moveSpeed)] === 0) posX -= dirX * moveSpeed; if (map[Math.floor(posY - dirY * moveSpeed)][Math.floor(posX)] === 0) posY -= dirY * moveSpeed; } // Rotate left if (keys['ArrowLeft'] || keys['a']) { const oldDirX = dirX; dirX = dirX * Math.cos(rotSpeed) - dirY * Math.sin(rotSpeed); dirY = oldDirX * Math.sin(rotSpeed) + dirY * Math.cos(rotSpeed); const oldPlaneX = planeX; planeX = planeX * Math.cos(rotSpeed) - planeY * Math.sin(rotSpeed); planeY = oldPlaneX * Math.sin(rotSpeed) + planeY * Math.cos(rotSpeed); } // Rotate right if (keys['ArrowRight'] || keys['d']) { const oldDirX = dirX; dirX = dirX * Math.cos(-rotSpeed) - dirY * Math.sin(-rotSpeed); dirY = oldDirX * Math.sin(-rotSpeed) + dirY * Math.cos(-rotSpeed); const oldPlaneX = planeX; planeX = planeX * Math.cos(-rotSpeed) - planeY * Math.sin(-rotSpeed); planeY = oldPlaneX * Math.sin(-rotSpeed) + planeY * Math.cos(-rotSpeed); } } // Render function function render() { // Clear the screen ctx.fillStyle = '#000'; ctx.fillRect(0, 0, canvas.width, canvas.height); for (let x = 0; x < canvas.width; x++) { // Calculate ray position and direction const cameraX = 2 * x / canvas.width - 1; // x-coordinate in camera space const rayDirX = dirX + planeX * cameraX; const rayDirY = dirY + planeY * cameraX; // Which box of the map we're in let mapX = Math.floor(posX); let mapY = Math.floor(posY); // Length of ray from current position to next x or y-side let sideDistX; let sideDistY; // Length of ray from one x or y-side to next x or y-side const deltaDistX = Math.abs(1 / rayDirX); const deltaDistY = Math.abs(1 / rayDirY); let perpWallDist; // Direction to go in x and y let stepX; let stepY; let hit = 0; // Was there a wall hit? let side; // NS or EW wall // Calculate step and initial sideDist if (rayDirX < 0) { stepX = -1; sideDistX = (posX - mapX) * deltaDistX; } else { stepX = 1; sideDistX = (mapX + 1.0 - posX) * deltaDistX; } if (rayDirY < 0) { stepY = -1; sideDistY = (posY - mapY) * deltaDistY; } else { stepY = 1; sideDistY = (mapY + 1.0 - posY) * deltaDistY; } // Perform DDA (Digital Differential Analysis) while (hit === 0) { // Jump to next map square, either in x-direction or y-direction if (sideDistX < sideDistY) { sideDistX += deltaDistX; mapX += stepX; side = 0; } else { sideDistY += deltaDistY; mapY += stepY; side = 1; } // Check if ray has hit a wall if (map[mapY][mapX] > 0) hit = 1; } // Calculate distance projected on camera direction if (side === 0) { perpWallDist = (mapX - posX + (1 - stepX) / 2) / rayDirX; } else { perpWallDist = (mapY - posY + (1 - stepY) / 2) / rayDirY; } // Calculate height of line to draw on screen const lineHeight = (canvas.height / perpWallDist); // Calculate lowest and highest pixel to fill in current stripe let drawStart = -lineHeight / 2 + canvas.height / 2; if (drawStart < 0) drawStart = 0; let drawEnd = lineHeight / 2 + canvas.height / 2; if (drawEnd >= canvas.height) drawEnd = canvas.height - 1; // Choose wall color let color; if (map[mapY][mapX] === 1) { color = side === 1 ? '#7F7F7F' : '#FFFFFF'; // Shade the wall color based on side } // Draw the vertical line ctx.fillStyle = color; ctx.fillRect(x, drawStart, 1, drawEnd - drawStart); } // Draw floor and ceiling ctx.fillStyle = '#888888'; ctx.fillRect(0, canvas.height / 2, canvas.width, canvas.height / 2); ctx.fillStyle = '#444444'; ctx.fillRect(0, 0, canvas.width, canvas.height / 2); } // Start the game loop gameLoop();
How It Works
1. Map Representation
The game world is represented as a 2D array called
map. Each element in the array corresponds to a tile in the game world:0represents empty space (no wall).1represents a wall.
2. Player Variables
posXandposYrepresent the player's position in the world.dirXanddirYrepresent the player's direction vector.planeXandplaneYare perpendicular to the direction vector and represent the 2D camera plane (used for the field of view).
3. Movement and Controls
The game listens for keyboard events to update the player's movement:
- Move Forward/Backward:
ArrowUporwandArrowDownors. - Rotate Left/Right:
ArrowLeftoraandArrowRightord.
The
update()function handles movement logic, checking for collisions with walls.4. Raycasting Algorithm
The core of the rendering happens in the
render()function using the raycasting technique:- For each vertical stripe (
x) of the screen, a ray is cast into the game world. - The ray advances step by step until it hits a wall (
hitbecomes1). - The distance to the wall (
perpWallDist) is calculated to determine the height of the wall slice to draw. - The wall slice is drawn as a vertical line on the canvas.
5. Drawing to the Canvas
- Walls are drawn with shading applied to give a sense of depth; walls facing different directions have different brightness.
- The floor and ceiling are drawn with solid colors to fill the space below and above the walls.
6. Game Loop
The
gameLoop()function runs continuously usingrequestAnimationFrame, callingupdate()andrender()every frame to keep the game running smoothly.Running the Game
To run the game:
- Create the Files: Save the HTML code as
index.htmland the JavaScript code asgame.jsin the same directory. - Open in Browser: Open
index.htmlin a modern web browser (such as Chrome or Firefox). - Controls: Use the arrow keys or
W,A,S,Dto move around the environment.
Further Enhancements
This basic implementation provides a foundation that you can build upon. Here are some ideas for expanding the game:
- Textures: Incorporate textures for walls to make the environment more detailed.
- Sprites: Add items or enemies as sprites within the game world.
- Collision Detection: Improve collision detection to handle edge cases.
- Mouse Controls: Use mouse movement for looking around.
- Lighting: Implement dynamic lighting effects.
- Sound: Add sound effects for a more immersive experience.
- Levels: Create more complex maps and allow the player to advance through levels.
- Enemy AI: Introduce enemies with basic AI for interaction.
- HUD: Add a heads-up display (HUD) to show player stats like health.
Learning Resources
To delve deeper into game development and raycasting, you might find these resources helpful:
- Raycasting Tutorials: Look up tutorials on raycasting engines for more detailed explanations.
- Game Development Books: Books on JavaScript game development can provide structured learning.
- Online Communities: Join forums or communities dedicated to game development for support.
Conclusion
Creating a Doom-style game is a complex task, but starting with a simple raycasting engine is an excellent way to learn about 3D rendering techniques in JavaScript. By understanding and experimenting with the code provided, you can gradually build up a more feature-rich game.
Feel free to ask if you have any questions or need further guidance on specific features!