Write 3D maze using raycasting, make the maze randomly generated, and make the player move with an on-screen analog instead of WASD, and move the camera around by swiping on the right side of the screen
Assistant
Creating a 3D maze using raycasting with a randomly generated layout, on-screen analog controls for movement, and swipe gestures for camera rotation is an exciting project! Below is a comprehensive guide to help you build this using HTML5 Canvas and JavaScript. We'll break this down into the following steps:
Setup the Project Structure
Generate a Random Maze
Implement Raycasting for 3D Rendering
Create On-Screen Analog Controls for Movement
Add Swipe Controls for Camera Rotation
Putting It All Together
Let's dive into each step.
1. Setup the Project Structure
First, set up your HTML, CSS, and JavaScript files.
We'll implement the functionality here. We'll cover this in the subsequent sections.
2. Generate a Random Maze
We'll use the Recursive Backtracker algorithm to generate a maze. Represent the maze as a 2D grid where 1 is a wall and 0 is a path.
Maze Generation Code
javascript
// main.js
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Resize canvas to full window size
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Maze parameters
const MAP_WIDTH = 15;
const MAP_HEIGHT = 15;
const CELL_SIZE = 64;
// Create maze grid
let maze = [];
for (let y = 0; y < MAP_HEIGHT; y++) {
let row = [];
for (let x = 0; x < MAP_WIDTH; x++) {
row.push(1); // Initialize all walls
}
maze.push(row);
}
// Directions: [dx, dy]
const directions = [
[0, -2],
[2, 0],
[0, 2],
[-2, 0]
];
// Recursive Backtracker Algorithm
function generateMaze(x, y) {
maze[y][x] = 0; // Mark current cell as path
// Shuffle directions
let dirs = directions.sort(() => Math.random() - 0.5);
for (let dir of dirs) {
const nx = x + dir[0];
const ny = y + dir[1];
if (nx > 0 && nx < MAP_WIDTH && ny > 0 && ny < MAP_HEIGHT && maze[ny][nx] === 1) {
maze[ny][nx] = 0; // Path to next cell
maze[y + dir[1]/2][x + dir[0]/2] = 0; // Remove wall between
generateMaze(nx, ny);
}
}
}
// Start maze generation from (1,1)
generateMaze(1,1);
// Debug: Draw the maze on the canvas (2D view)
function drawMaze2D() {
for (let y = 0; y < MAP_HEIGHT; y++) {
for (let x = 0; x < MAP_WIDTH; x++) {
if (maze[y][x] === 1) {
ctx.fillStyle = '#444';
ctx.fillRect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE);
} else {
ctx.fillStyle = '#fff';
ctx.fillRect(x * CELL_SIZE, y * CELL_SIZE, CELL_SIZE, CELL_SIZE);
}
}
}
}
// Uncomment to see the 2D maze
// drawMaze2D();
This code initializes a maze and generates it using the recursive backtracker algorithm. For now, there's a drawMaze2D function to visualize the maze in 2D (which is commented out). We'll proceed to implement raycasting for 3D rendering.
3. Implement Raycasting for 3D Rendering
Raycasting is a technique used to render 3D environments on a 2D screen by casting rays from the player's viewpoint and detecting wall intersections. Here's a basic implementation adapted from classic raycasters like the one used in Wolfenstein 3D.
Raycasting Code
javascript
// main.js (continued)
// Player parameters
let player = {
x: CELL_SIZE * 1.5, // Starting X position
y: CELL_SIZE * 1.5, // Starting Y position
angle: 0, // Direction player is facing in radians
fov: Math.PI / 3, // Field of view (60 degrees)
moveSpeed: 2, // Movement speed
rotSpeed: 0.03 // Rotation speed
};
// Raycasting parameters
const NUM_RAYS = 300;
const MAX_DEPTH = MAP_WIDTH * CELL_SIZE;
// Draw the 3D view
function draw3D() {
for (let i = 0; i < NUM_RAYS; i++) {
// Calculate ray angle
let rayAngle = (player.angle - player.fov / 2) + (player.fov) * (i / NUM_RAYS);
rayAngle = normalizeAngle(rayAngle);
// Cast the ray and get distance
let distance = castRay(player.x, player.y, rayAngle);
// Correct the fish-eye effect
distance *= Math.cos(player.angle - rayAngle);
// Calculate wall height
let wallHeight = (CELL_SIZE / distance) * (canvas.width / (2 * Math.tan(player.fov / 2)));
// Determine color based on distance
let colorIntensity = 255 - Math.min(255, distance * 10);
ctx.fillStyle = `rgb(${colorIntensity}, ${colorIntensity}, ${colorIntensity})`;
// Draw vertical slice
let sliceWidth = canvas.width / NUM_RAYS;
ctx.fillRect(i * sliceWidth, (canvas.height / 2) - wallHeight / 2, sliceWidth, wallHeight);
}
}
// Normalize angle between 0 and 2*PI
function normalizeAngle(angle) {
angle = angle % (2 * Math.PI);
if (angle < 0) angle += 2 * Math.PI;
return angle;
}
// Cast a single ray and return distance to the wall
function castRay(x, y, angle) {
let stepSize = 5; // Increment size for ray
let distance = 0;
while (distance < MAX_DEPTH) {
distance += stepSize;
let testX = x + Math.cos(angle) * distance;
let testY = y + Math.sin(angle) * distance;
// Check if out of bounds
if (testX < 0 || testX >= MAP_WIDTH * CELL_SIZE || testY < 0 || testY >= MAP_HEIGHT * CELL_SIZE) {
return distance;
}
// Check if hit a wall
if (maze[Math.floor(testY / CELL_SIZE)][Math.floor(testX / CELL_SIZE)] === 1) {
return distance;
}
}
return distance;
}
// Draw player view
function renderFrame() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
draw3D();
requestAnimationFrame(renderFrame);
}
// Start rendering
renderFrame();
Explanation:
Player Object: Tracks the player's position, viewing angle, field of view, movement speed, and rotation speed.
Raycasting Loop: For each of the NUM_RAYS, calculate the angle of the ray, cast it to find the distance to the nearest wall, correct for the fish-eye effect, determine wall height based on distance, set the color intensity based on distance, and draw a vertical slice representing the wall.
Ray Casting Function (castRay): Step through the environment in small increments (stepSize) along the ray's angle until a wall is hit or the maximum depth is reached.
Rendering (renderFrame): Clears the canvas and draws the 3D view on each frame using requestAnimationFrame for smooth updates.
Note: This is a basic raycaster and can be optimized further. Additionally, shading, texture mapping, and more advanced features can be added for better visuals.
4. Create On-Screen Analog Controls for Movement
We'll implement a virtual joystick for player movement (forward and backward, and possibly strafing) instead of using keyboard controls. For simplicity, we'll handle basic forward and backward movement.
Implementing the Virtual Joystick
We'll use touch events to detect joystick movements. Here's a simple implementation:
javascript
// main.js (continued)
// Movement variables
let moveDirection = 0; // 1 for forward, -1 for backward, 0 for no movement
// Setup joystick
const joystick = document.getElementById('joystick');
// Handle touch/mouse events for joystick
let joystickActive = false;
let joystickStart = { x: 0, y: 0 };
let joystickCurrent = { x: 0, y: 0 };
joystick.addEventListener('pointerdown', (e) => {
joystickActive = true;
joystickStart.x = e.clientX;
joystickStart.y = e.clientY;
});
joystick.addEventListener('pointermove', (e) => {
if (!joystickActive) return;
joystickCurrent.x = e.clientX;
joystickCurrent.y = e.clientY;
// Calculate movement direction based on joystick position
let deltaY = joystickStart.y - joystickCurrent.y;
if (deltaY > 10) {
moveDirection = 1; // Forward
} else if (deltaY < -10) {
moveDirection = -1; // Backward
} else {
moveDirection = 0; // No movement
}
});
joystick.addEventListener('pointerup', () => {
joystickActive = false;
moveDirection = 0;
joystickCurrent = { x: joystickStart.x, y: joystickStart.y };
});
// Update player position based on moveDirection
function updatePlayer() {
if (moveDirection !== 0) {
let moveStep = player.moveSpeed * moveDirection;
let newX = player.x + Math.cos(player.angle) * moveStep;
let newY = player.y + Math.sin(player.angle) * moveStep;
// Collision detection
if (!isWall(newX, player.y)) {
player.x = newX;
}
if (!isWall(player.x, newY)) {
player.y = newY;
}
}
}
// Check if a position is a wall
function isWall(x, y) {
if (x < 0 || x >= MAP_WIDTH * CELL_SIZE || y < 0 || y >= MAP_HEIGHT * CELL_SIZE) {
return true;
}
return maze[Math.floor(y / CELL_SIZE)][Math.floor(x / CELL_SIZE)] === 1;
}
// Modify renderFrame to include updating player
function renderFrameWithMovement() {
updatePlayer();
ctx.clearRect(0, 0, canvas.width, canvas.height);
draw3D();
requestAnimationFrame(renderFrameWithMovement);
}
renderFrameWithMovement();
Explanation:
Joystick DOM Element: A div that acts as the joystick area. It's positioned at the bottom-left corner.
Touch/Pointer Events:
pointerdown: Activates the joystick and records the starting touch position.
pointermove: Calculates the movement direction based on the vertical movement of the touch. If the touch moves upwards beyond a threshold, the player moves forward; if downwards, backward.
pointerup: Deactivates the joystick and stops movement.
Movement Logic (updatePlayer): Updates the player's position based on the moveDirection. It checks for collisions to prevent walking through walls.
Rendering Loop Update: Modified the rendering loop to include updating the player's position before drawing the frame.
Visual Feedback (Optional):
For a better user experience, you can add visual feedback to the joystick, such as showing the joystick's handle moving within the base circle. This requires additional drawing and handling within the touch events.
5. Add Swipe Controls for Camera Rotation
We'll use touch events on a designated swipe area to rotate the player's view direction by changing the player.angle.
Implementing Swipe for Rotation
javascript
// main.js (continued)
// Rotation variables
let rotationDelta = 0;
// Setup swipe area
const swipeArea = document.getElementById('swipeArea');
// Handle touch/mouse events for swipe
let isSwiping = false;
let swipeStartX = 0;
let swipeStartY = 0;
swipeArea.addEventListener('pointerdown', (e) => {
isSwiping = true;
swipeStartX = e.clientX;
swipeStartY = e.clientY;
});
swipeArea.addEventListener('pointermove', (e) => {
if (!isSwiping) return;
let deltaX = e.clientX - swipeStartX;
// Adjust sensitivity as needed
rotationDelta = deltaX * 0.002;
});
swipeArea.addEventListener('pointerup', () => {
isSwiping = false;
rotationDelta = 0;
});
// Update player angle based on rotationDelta
function updateRotation() {
player.angle += rotationDelta;
player.angle = normalizeAngle(player.angle);
}
// Modify renderFrame to include updating rotation
function renderFullFrame() {
updatePlayer();
updateRotation();
ctx.clearRect(0, 0, canvas.width, canvas.height);
draw3D();
requestAnimationFrame(renderFullFrame);
}
renderFullFrame();
Explanation:
Swipe Area DOM Element: A div positioned at the bottom-right corner to capture swipe gestures.
Touch/Pointer Events:
pointerdown: Activates the swipe and records the starting position.
pointermove: Calculates the horizontal movement of the swipe and translates it into rotation delta. Adjust the multiplier (0.002) to change rotation sensitivity.
pointerup: Deactivates the swipe and resets rotation delta.
Rotation Logic (updateRotation): Updates the player’s angle based on the rotationDelta. Ensures the angle stays within 0 to 2π radians.
Rendering Loop Update: Modified the rendering loop to include updating the player’s rotation before drawing each frame.
Enhancements (Optional):
Visual Indication: You can show arrows or other visual indicators on the swipe area to guide the user.
Rotation Smoothing: Implement smoothing algorithms to make rotation feel more natural.
6. Putting It All Together
Here's the complete main.js combining all the above steps:
javascript
Final Notes:
Performance Optimization: For larger mazes or higher resolutions, consider optimizing the raycasting implementation. Techniques include stepping through the grid rather than fixed increments or limiting the maximum number of steps.
Enhancements:
Textures: Apply textures to the walls for a more realistic appearance.
Floor and Ceiling: Add simple shading or color gradients to represent the floor and ceiling.
Minimap: Implement a 2D minimap to help the player navigate.
Collision Smoothing: Improve collision detection to allow smoother movement near walls.
Cross-Platform Considerations: Ensure touch controls are responsive across different devices and screen sizes.
Styling Controls: Enhance the visual appearance of the joystick and swipe area for a better user experience.
Conclusion
You've now built a basic 3D maze game using raycasting with a randomly generated maze, on-screen analog controls for movement, and swipe gestures for camera rotation. This foundational setup can be further expanded with additional features, optimizations, and visual enhancements to create a more immersive and polished game.
Feel free to experiment with the parameters, add new features, and optimize the code to suit your needs. Happy coding!
Not yet included in a published release.
// main.js
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Resize canvas to full window size
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Maze parameters
const MAP_WIDTH = 15;
const MAP_HEIGHT = 15;
const CELL_SIZE = 64;
// Create maze grid
let maze = [];
for (let y = 0; y < MAP_HEIGHT; y++) {
let row = [];
for (let x = 0; x < MAP_WIDTH; x++) {
row.push(1); // Initialize all walls
}
maze.push(row);
}
// Directions: [dx, dy]
const directions = [
[0, -2],
[2, 0],
[0, 2],
[-2, 0]
];
// Recursive Backtracker Algorithm
function generateMaze(x, y) {
maze[y][x] = 0; // Mark current cell as path
// Shuffle directions
let dirs = directions.sort(() => Math.random() - 0.5);
for (let dir of dirs) {
const nx = x + dir[0];
const ny = y + dir[1];
if (nx > 0 && nx < MAP_WIDTH && ny > 0 && ny < MAP_HEIGHT && maze[ny][nx] === 1) {
maze[ny][nx] = 0; // Path to next cell
maze[y + dir[1]/2][x + dir[0]/2] = 0; // Remove wall between
generateMaze(nx, ny);
}
}
}
// Start maze generation from (1,1)
generateMaze(1,1);
// Player parameters
let player = {
x: CELL_SIZE * 1.5, // Starting X position
y: CELL_SIZE * 1.5, // Starting Y position
angle: 0, // Direction player is facing in radians
fov: Math.PI / 3, // Field of view (60 degrees)
moveSpeed: 2, // Movement speed
rotSpeed: 0.03 // Rotation speed
};
// Raycasting parameters
const NUM_RAYS = 300;
const MAX_DEPTH = MAP_WIDTH * CELL_SIZE;
// Normalize angle between 0 and 2*PI
function normalizeAngle(angle) {
angle = angle % (2 * Math.PI);
if (angle < 0) angle += 2 * Math.PI;
return angle;
}
// Cast a single ray and return distance to the wall
function castRay(x, y, angle) {
let stepSize = 5; // Increment size for ray
let distance = 0;
while (distance < MAX_DEPTH) {
distance += stepSize;
let testX = x + Math.cos(angle) * distance;
let testY = y + Math.sin(angle) * distance;
// Check if out of bounds
if (testX < 0 || testX >= MAP_WIDTH * CELL_SIZE || testY < 0 || testY >= MAP_HEIGHT * CELL_SIZE) {
return distance;
}
// Check if hit a wall
if (maze[Math.floor(testY / CELL_SIZE)][Math.floor(testX / CELL_SIZE)] === 1) {
return distance;
}
}
return distance;
}
// Draw the 3D view
function draw3D() {
for (let i = 0; i < NUM_RAYS; i++) {
// Calculate ray angle
let rayAngle = (player.angle - player.fov / 2) + (player.fov) * (i / NUM_RAYS);
rayAngle = normalizeAngle(rayAngle);
// Cast the ray and get distance
let distance = castRay(player.x, player.y, rayAngle);
// Correct the fish-eye effect
distance *= Math.cos(player.angle - rayAngle);
// Calculate wall height
let wallHeight = (CELL_SIZE / distance) * (canvas.width / (2 * Math.tan(player.fov / 2)));
// Determine color based on distance
let colorIntensity = 255 - Math.min(255, distance * 10);
ctx.fillStyle = `rgb(${colorIntensity}, ${colorIntensity}, ${colorIntensity})`;
// Draw vertical slice
let sliceWidth = canvas.width / NUM_RAYS;
ctx.fillRect(i * sliceWidth, (canvas.height / 2) - wallHeight / 2, sliceWidth, wallHeight);
}
}
// Check if a position is a wall
function isWall(x, y) {
if (x < 0 || x >= MAP_WIDTH * CELL_SIZE || y < 0 || y >= MAP_HEIGHT * CELL_SIZE) {
return true;
}
return maze[Math.floor(y / CELL_SIZE)][Math.floor(x / CELL_SIZE)] === 1;
}
// Movement variables
let moveDirection = 0; // 1 for forward, -1 for backward, 0 for no movement
// Setup joystick
const joystick = document.getElementById('joystick');
// Handle touch/mouse events for joystick
let joystickActive = false;
let joystickStart = { x: 0, y: 0 };
let joystickCurrent = { x: 0, y: 0 };
joystick.addEventListener('pointerdown', (e) => {
joystickActive = true;
joystickStart.x = e.clientX;
joystickStart.y = e.clientY;
e.preventDefault();
});
joystick.addEventListener('pointermove', (e) => {
if (!joystickActive) return;
joystickCurrent.x = e.clientX;
joystickCurrent.y = e.clientY;
// Calculate movement direction based on joystick position
let deltaY = joystickStart.y - joystickCurrent.y;
if (deltaY > 15) {
moveDirection = 1; // Forward
} else if (deltaY < -15) {
moveDirection = -1; // Backward
} else {
moveDirection = 0; // No movement
}
e.preventDefault();
});
joystick.addEventListener('pointerup', () => {
joystickActive = false;
moveDirection = 0;
joystickCurrent = { x: joystickStart.x, y: joystickStart.y };
});
// Rotation variables
let rotationDelta = 0;
// Setup swipe area
const swipeArea = document.getElementById('swipeArea');
// Handle touch/mouse events for swipe
let isSwiping = false;
let swipeStartX = 0;
let swipeStartY = 0;
swipeArea.addEventListener('pointerdown', (e) => {
isSwiping = true;
swipeStartX = e.clientX;
swipeStartY = e.clientY;
e.preventDefault();
});
swipeArea.addEventListener('pointermove', (e) => {
if (!isSwiping) return;
let deltaX = e.clientX - swipeStartX;
// Adjust sensitivity as needed
rotationDelta = deltaX * 0.002;
swipeStartX = e.clientX; // Update for continuous rotation
swipeStartY = e.clientY;
e.preventDefault();
});
swipeArea.addEventListener('pointerup', () => {
isSwiping = false;
rotationDelta = 0;
});
// Update player position based on moveDirection
function updatePlayer() {
if (moveDirection !== 0) {
let moveStep = player.moveSpeed * moveDirection;
let newX = player.x + Math.cos(player.angle) * moveStep;
let newY = player.y + Math.sin(player.angle) * moveStep;
// Collision detection
if (!isWall(newX, player.y)) {
player.x = newX;
}
if (!isWall(player.x, newY)) {
player.y = newY;
}
}
}
// Update player angle based on rotationDelta
function updateRotation() {
if (rotationDelta !== 0) {
player.angle += rotationDelta;
player.angle = normalizeAngle(player.angle);
}
}
// Rendering loop
function renderFullFrame() {
updatePlayer();
updateRotation();
ctx.clearRect(0, 0, canvas.width, canvas.height);
draw3D();
requestAnimationFrame(renderFullFrame);
}
renderFullFrame();