Creating a simple raycasting engine from scratch using Pygame is a fantastic way to understand how early 3D rendering works, such as in classic games like Wolfenstein 3D. Below is a complete example of a basic raycasting game. This code visualizes the raycasting process by drawing lines (rays) and rendering walls based on a 2D map.
Features:
- 2D Grid Map: Defines walls and empty spaces.
- Player Movement: Move forward, backward, and rotate left/right.
- Raycasting Visualization: Rays are cast from the player's position to detect walls.
- Rendering: Walls are drawn based on ray distances to create a pseudo-3D view.
- Slow Rendering: Rays are drawn slowly to visualize the rendering process.
Prerequisites:
Make sure you have Pygame installed. You can install it using pip:
pip install pygame
Complete Code:
import pygame
import math
import sys
# Initialize Pygame
pygame.init()
# Screen dimensions
WIDTH = 800
HEIGHT = 600
HALF_HEIGHT = HEIGHT // 2
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
DARKGRAY = (110, 110, 110)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
# Map settings
MAP_WIDTH = 10
MAP_HEIGHT = 10
TILE_SIZE = 50
# Define the map (1 represents walls, 0 represents empty space)
game_map = [
[1,1,1,1,1,1,1,1,1,1],
[1,0,0,0,0,0,0,0,0,1],
[1,0,1,0,1,1,0,1,0,1],
[1,0,1,0,0,0,0,1,0,1],
[1,0,1,1,1,1,0,1,0,1],
[1,0,0,0,0,1,0,0,0,1],
[1,0,1,1,0,1,1,1,0,1],
[1,0,0,1,0,0,0,1,0,1],
[1,0,0,0,0,1,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1],
]
# Player settings
player_x = TILE_SIZE * 3
player_y = TILE_SIZE * 3
player_angle = 0
player_speed = 2
rot_speed = 0.04
# Raycasting settings
FOV = math.pi / 3 # 60 degrees field of view
NUM_RAYS = WIDTH // 2 # Number of rays
MAX_DEPTH = 800
# Create the Pygame screen
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Raycasting Visualization")
# Clock for controlling frame rate
clock = pygame.time.Clock()
def cast_ray(ray_angle):
"""
Cast a single ray and return the distance to the wall hit by the ray.
"""
# Normalize the angle
ray_angle = ray_angle % (2 * math.pi)
# Determine the step size and initial side distances
sin_a = math.sin(ray_angle)
cos_a = math.cos(ray_angle)
for depth in range(MAX_DEPTH):
target_x = player_x + depth * cos_a
target_y = player_y + depth * sin_a
map_x = int(target_x // TILE_SIZE)
map_y = int(target_y // TILE_SIZE)
if 0 <= map_x < MAP_WIDTH and 0 <= map_y < MAP_HEIGHT:
if game_map[map_y][map_x] == 1:
# Hit a wall
return depth, (target_x, target_y)
else:
break # Ray is out of bounds
return MAX_DEPTH, (target_x, target_y)
def draw_map():
"""
Draw the top-down map and player for visualization.
"""
for y in range(MAP_HEIGHT):
for x in range(MAP_WIDTH):
rect = pygame.Rect(x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE)
if game_map[y][x] == 1:
pygame.draw.rect(screen, DARKGRAY, rect)
else:
pygame.draw.rect(screen, BLACK, rect)
pygame.draw.rect(screen, DARKGRAY, rect, 1) # Grid lines
# Draw player
pygame.draw.circle(screen, GREEN, (int(player_x), int(player_y)), 5)
# Draw player's direction
dir_x = player_x + math.cos(player_angle) * 20
dir_y = player_y + math.sin(player_angle) * 20
pygame.draw.line(screen, GREEN, (player_x, player_y), (dir_x, dir_y), 2)
def render_3d():
"""
Render a simple 3D projection based on raycasting distances.
"""
for ray in range(NUM_RAYS):
# Calculate the current ray angle
ray_angle = (player_angle - FOV / 2) + (ray / NUM_RAYS) * FOV
# Cast the ray
depth, hit_point = cast_ray(ray_angle)
# Correct the fish-eye effect
depth *= math.cos(player_angle - ray_angle)
# Calculate wall height
if depth == 0:
depth = 0.0001 # Prevent division by zero
wall_height = min(int(500 / depth), HEIGHT)
# Determine color based on depth
shade = 255 / (1 + depth * depth * 0.0001)
color = (shade, shade, shade)
# Draw the vertical wall slice
pygame.draw.rect(screen, color, (ray * 2, HALF_HEIGHT - wall_height // 2, 2, wall_height))
def main():
global player_x, player_y, player_angle
running = True
while running:
clock.tick(60) # 60 FPS
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Handle keys
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
player_angle -= rot_speed
if keys[pygame.K_RIGHT]:
player_angle += rot_speed
if keys[pygame.K_UP]:
player_x += math.cos(player_angle) * player_speed
player_y += math.sin(player_angle) * player_speed
if keys[pygame.K_DOWN]:
player_x -= math.cos(player_angle) * player_speed
player_y -= math.sin(player_angle) * player_speed
# Prevent player from walking through walls
map_x = int(player_x // TILE_SIZE)
map_y = int(player_y // TILE_SIZE)
if game_map[map_y][map_x] == 1:
player_x -= math.cos(player_angle) * player_speed
player_y -= math.sin(player_angle) * player_speed
# Clear screen
screen.fill(BLACK)
# Draw the top-down map
draw_map()
# Create a surface for the 3D view
projection = pygame.Surface((WIDTH, HEIGHT))
projection.set_alpha(200)
projection.fill(BLACK)
# Cast and draw rays
for ray in range(NUM_RAYS):
ray_angle = (player_angle - FOV / 2) + (ray / NUM_RAYS) * FOV
depth, hit_point = cast_ray(ray_angle)
# Correct the fish-eye effect
depth *= math.cos(player_angle - ray_angle)
# Calculate wall height
if depth == 0:
depth = 0.0001 # Prevent division by zero
wall_height = min(int(500 / depth), HEIGHT)
# Determine color based on depth
shade = 255 / (1 + depth * depth * 0.0001)
color = (shade, shade, shade)
# Draw the vertical wall slice
pygame.draw.rect(projection, color, (ray * 2, HALF_HEIGHT - wall_height // 2, 2, wall_height))
# Optionally, draw the rays on the map for visualization
# Uncomment the lines below to see the rays on the top-down map
# end_x = hit_point[0]
# end_y = hit_point[1]
# pygame.draw.line(screen, RED, (player_x, player_y), (end_x, end_y), 1)
# Slow down the rendering to visualize
pygame.display.flip()
# To slow down the ray rendering, uncomment the following line
# pygame.time.wait(1)
# Blit the projection (3D view) onto the screen
screen.blit(projection, (0, 0))
# Optionally, draw the 3D view on the right half of the screen
# Uncomment the lines below to separate the map and 3D view
# screen.blit(projection, (0, 0))
# Update the display
pygame.display.flip()
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
Explanation of the Code:
-
Initialization:
- Set up Pygame, screen dimensions, colors, and the map.
- Define the player's starting position, angle, and movement speeds.
-
Map Representation:
- The
game_map is a 2D list where 1 represents walls and 0 represents empty spaces.
-
Raycasting Function (cast_ray):
- Casts a single ray at a given angle.
- Increments the depth until it hits a wall or reaches the maximum depth.
- Returns the distance to the wall and the hit point coordinates.
-
Drawing the Map (draw_map):
- Renders the top-down 2D map, walls, and the player's position and direction.
-
Rendering the 3D View (render_3d):
- Iterates through each ray, casts it, and draws vertical slices to create a 3D effect.
- This function is simplified in the main loop for better control over rendering speed.
-
Main Loop (main):
- Handles user input for moving and rotating the player.
- Prevents the player from walking through walls by checking the map.
- Clears the screen, draws the map, and performs raycasting.
- Optionally, you can visualize rays on the top-down map by uncommenting relevant lines.
- To slow down the rendering of rays and visualize them step-by-step, you can uncomment the
pygame.time.wait(1) line inside the raycasting loop.
-
Running the Game:
- The game runs at 60 FPS, allowing smooth movement and rendering.
- Use the arrow keys to move:
- Left/Right: Rotate the player's view.
- Up/Down: Move forward and backward.
Enhancements:
-
Visualizing Rays: To see the rays being cast in real-time on the top-down map, uncomment the lines within the raycasting loop that draw red lines.
-
Adjust Rendering Speed: Modify or uncomment the pygame.time.wait(1) line to slow down the rendering process, allowing you to see each ray being drawn step-by-step.
-
Shading and Textures: Currently, walls are shaded based on distance. You can enhance the visuals by adding textures or more sophisticated shading techniques.
-
Collision Detection: The current collision detection is basic. For more accurate collision handling, consider using bounding boxes or circles.
Running the Code:
Save the code to a file, for example, raycasting.py, and run it using Python:
python raycasting.py
You should see a window displaying a top-down map on which you can move the player. The 3D view is rendered showing the walls as you navigate the map. The raycasting process can be visualized by adjusting the rendering speed or displaying the rays directly on the map.
This example provides a foundational understanding of raycasting and 3D rendering. From here, you can expand the engine by adding features like textures, sprite rendering, lighting effects, and more complex maps.