Certainly! I've reviewed your code and found some areas where bugs can occur and where improvements can be made. Below, I'll outline the issues and provide solutions to fix them. Additionally, I'll suggest some enhancements to improve the overall performance and accuracy of your raycasting engine.
1. Index Out of Bounds in Raycasting Function
Issue: In the cast_ray() function, when the ray extends beyond the map boundaries, accessing MAP[test_cell_y][test_cell_x] can lead to an IndexError.
Solution: Add boundary checks before accessing the MAP array to ensure test_cell_x and test_cell_y are within valid ranges.
Improved cast_ray() Function with Boundary Checks:
def cast_ray(angle):
ray_x = math.cos(angle)
ray_y = math.sin(angle)
distance = 0
while distance < MAX_DEPTH:
distance += 1
ray_end_x = player_x + ray_x * distance
ray_end_y = player_y + ray_y * distance
test_cell_x = int(ray_end_x / CELL_SIZE)
test_cell_y = int(ray_end_y / CELL_SIZE)
# Check that test_cell_x and test_cell_y are within the map boundaries
if 0 <= test_cell_x < len(MAP[0]) and 0 <= test_cell_y < len(MAP):
if MAP[test_cell_y][test_cell_x] > 0:
if abs(ray_end_x % CELL_SIZE) < 1:
texture_pos = ray_end_y % CELL_SIZE / CELL_SIZE
else:
texture_pos = ray_end_x % CELL_SIZE / CELL_SIZE
return distance, angle, MAP[test_cell_y][test_cell_x], texture_pos
else:
break # Ray is outside the map
return distance, angle, 0, 0
2. Index Out of Bounds in Movement Code
Issue: Similar to the raycasting function, moving the player can cause an IndexError when checking for collisions at the new position if it's outside the map boundaries.
Solution: Add boundary checks before accessing the MAP array during player movement.
Improved Movement Code with Boundary Checks:
# Player movement
if keys[pygame.K_UP]:
next_x = player_x + math.cos(player_angle) * current_speed
next_y = player_y + math.sin(player_angle) * current_speed
next_cell_x = int(next_x / CELL_SIZE)
next_cell_y = int(next_y / CELL_SIZE)
if 0 <= next_cell_x < len(MAP[0]) and 0 <= next_cell_y < len(MAP):
if MAP[next_cell_y][next_cell_x] == 0:
player_x = next_x
player_y = next_y
if keys[pygame.K_DOWN]:
next_x = player_x - math.cos(player_angle) * current_speed
next_y = player_y - math.sin(player_angle) * current_speed
next_cell_x = int(next_x / CELL_SIZE)
next_cell_y = int(next_y / CELL_SIZE)
if 0 <= next_cell_x < len(MAP[0]) and 0 <= next_cell_y < len(MAP):
if MAP[next_cell_y][next_cell_x] == 0:
player_x = next_x
player_y = next_y
3. Implementing the DDA Algorithm for Raycasting
Issue: The current raycasting method increments the distance by 1 unit, which can be inefficient and less accurate.
Solution: Implement the Digital Differential Analyzer (DDA) algorithm for more precise and efficient raycasting.
Improved cast_ray() Function Using DDA:
def cast_ray(angle):
sin_a = math.sin(angle)
cos_a = math.cos(angle)
# Map dimensions
map_width = len(MAP[0])
map_height = len(MAP)
# Player's current cell
player_cell_x = int(player_x / CELL_SIZE)
player_cell_y = int(player_y / CELL_SIZE)
# Calculate step and initial side distances
if cos_a == 0:
delta_dist_x = float('inf')
step_x = 0
side_dist_x = float('inf')
else:
delta_dist_x = abs(CELL_SIZE / cos_a)
step_x = 1 if cos_a >= 0 else -1
side_dist_x = ((player_cell_x + (step_x > 0)) * CELL_SIZE - player_x) / cos_a
if sin_a == 0:
delta_dist_y = float('inf')
step_y = 0
side_dist_y = float('inf')
else:
delta_dist_y = abs(CELL_SIZE / sin_a)
step_y = 1 if sin_a >= 0 else -1
side_dist_y = ((player_cell_y + (step_y > 0)) * CELL_SIZE - player_y) / sin_a
while True:
if side_dist_x < side_dist_y:
side_dist_x += delta_dist_x
player_cell_x += step_x
side = 0 # Vertical wall
else:
side_dist_y += delta_dist_y
player_cell_y += step_y
side = 1 # Horizontal wall
# Boundary check
if 0 <= player_cell_x < map_width and 0 <= player_cell_y < map_height:
wall_type = MAP[player_cell_y][player_cell_x]
if wall_type > 0:
# Calculate distance
if side == 0:
distance = (player_cell_x * CELL_SIZE - player_x + (1 - step_x) * CELL_SIZE / 2) / cos_a
texture_pos = (player_y + distance * sin_a) % CELL_SIZE / CELL_SIZE
else:
distance = (player_cell_y * CELL_SIZE - player_y + (1 - step_y) * CELL_SIZE / 2) / sin_a
texture_pos = (player_x + distance * cos_a) % CELL_SIZE / CELL_SIZE
return distance, angle, wall_type, texture_pos
else:
# Ray is out of bounds
return MAX_DEPTH, angle, 0, 0
if distance >= MAX_DEPTH:
# Max depth reached
return MAX_DEPTH, angle, 0, 0
4. Adjusting Field of View and Number of Rays
Issue: The NUM_RAYS might not correspond to the SCREEN_WIDTH, which can cause rendering artifacts.
Solution: Set NUM_RAYS equal to SCREEN_WIDTH to ensure each column represents a ray, providing a one-to-one mapping between rays and screen pixels.
Updated Variables:
NUM_RAYS = SCREEN_WIDTH # Now, each screen column corresponds to a ray
5. Improving Texture Rendering
Issue: Scaling textures for each wall slice can be performance-intensive.
Solution: Precompute scaled textures or optimize the drawing function to minimize scaling operations.
Improved Texture Drawing in draw_scene():
def draw_scene():
screen.fill(CEILING_COLOR, (0, 0, SCREEN_WIDTH, SCREEN_HEIGHT // 2))
screen.fill(FLOOR_COLOR, (0, SCREEN_HEIGHT // 2, SCREEN_WIDTH, SCREEN_HEIGHT // 2))
for x in range(NUM_RAYS):
ray_angle = (player_angle - HALF_FOV) + (x / NUM_RAYS) * FOV
distance, angle, wall_type, texture_pos = cast_ray(ray_angle)
if wall_type > 0:
distance *= math.cos(angle - player_angle) # Remove fish-eye effect
wall_height = (CELL_SIZE * SCREEN_HEIGHT) / (distance + 0.0001)
wall_top = (SCREEN_HEIGHT - wall_height) / 2
wall_bottom = wall_top + wall_height
# Get wall texture and sample the correct vertical slice
texture = texture_cache.wall_textures[wall_type]
texture_x = int(texture_pos * (TEXTURE_SIZE - 1))
column = texture.subsurface(texture_x, 0, 1, TEXTURE_SIZE)
column = pygame.transform.scale(column, (1, int(wall_height)))
# Apply fog effect
fog_factor = max(0, min(1, (MAX_DEPTH - distance) / MAX_DEPTH))
if fog_factor < 1:
column.set_alpha(int(255 * fog_factor))
screen.blit(column, (x, wall_top))
6. Adjusting Movement and Rotation Speeds
Issue: Multiplying by dt * 60 might not correctly compensate for frame rate variations.
Solution: Use dt directly to ensure movement and rotation speeds are consistent across different frame rates.
Updated Movement and Rotation Code:
current_speed = player_speed * dt
current_rotation = rotation_speed * dt
7. Optimizing Texture Cache
Issue: The get_scaled_texture() function scales textures for every different height, leading to a large number of cached textures.
Solution: Instead of caching scaled textures for every possible height, sample the texture column directly and scale it to the appropriate wall height during rendering.
Updated TextureCache Class:
class TextureCache:
def __init__(self):
self.wall_textures = {}
self._generate_textures()
def _generate_textures(self):
for wall_type, pattern in WALL_TEXTURES.items():
surface = pygame.Surface((TEXTURE_SIZE, TEXTURE_SIZE))
for y in range(TEXTURE_SIZE):
for x in range(TEXTURE_SIZE):
shade = int(min(255, max(0, pattern[y][x])))
surface.set_at((x, y), (shade, shade, shade))
self.wall_textures[wall_type] = surface.convert()
8. Summary of Changes
- Fixed Index Errors: Added boundary checks in
cast_ray() and movement code to prevent IndexError.
- Implemented DDA Algorithm: Rewrote the
cast_ray() function using the DDA algorithm for more accurate and efficient raycasting.
- Adjusted Ray and Screen Mapping: Set
NUM_RAYS to SCREEN_WIDTH to ensure each screen column corresponds to a ray.
- Optimized Texture Rendering: Modified texture handling in
draw_scene() to improve performance and visual quality.
- Consistent Movement Speed: Adjusted movement and rotation calculations to use
dt directly.
- Optimized Texture Cache: Simplified the
TextureCache class to reduce memory usage and improve performance.
Final Code
Below is the updated and improved code incorporating all the fixes and enhancements:
import pygame
import math
import numpy as np
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FOV = math.pi / 3 # Field of view (60 degrees)
HALF_FOV = FOV / 2
NUM_RAYS = SCREEN_WIDTH # One ray per screen column
MAX_DEPTH = 800
CELL_SIZE = 64
PLAYER_SIZE = 10
FLOOR_COLOR = (30, 30, 30)
CEILING_COLOR = (50, 50, 80)
TEXTURE_SIZE = 64
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (128, 128, 128)
WALL_TEXTURES = {
1: np.array([[(int((i ^ j) % 2) * 255) for i in range(TEXTURE_SIZE)] for j in range(TEXTURE_SIZE)], dtype=np.uint8),
2: np.array([[(int((i * j) % 32) * 8) for i in range(TEXTURE_SIZE)] for j in range(TEXTURE_SIZE)], dtype=np.uint8),
3: np.array([[int(abs(128 - i) * 2) for i in range(TEXTURE_SIZE)] for j in range(TEXTURE_SIZE)], dtype=np.uint8)
}
MAP = [
[1, 1, 1, 2, 2, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 1],
[1, 0, 3, 0, 2, 0, 0, 2],
[2, 0, 0, 0, 0, 3, 0, 1],
[2, 0, 2, 0, 0, 0, 0, 1],
[1, 0, 3, 0, 2, 0, 0, 2],
[1, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 2, 1, 1, 2, 1, 1]
]
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('2.5D Raycaster')
player_x = CELL_SIZE * 1.5
player_y = CELL_SIZE * 1.5
player_angle = 0
player_speed = 150 # Units per second
rotation_speed = 2 # Radians per second
class TextureCache:
def __init__(self):
self.wall_textures = {}
self._generate_textures()
def _generate_textures(self):
for wall_type, pattern in WALL_TEXTURES.items():
surface = pygame.Surface((TEXTURE_SIZE, TEXTURE_SIZE))
for y in range(TEXTURE_SIZE):
for x in range(TEXTURE_SIZE):
shade = int(min(255, max(0, pattern[y][x])))
surface.set_at((x, y), (shade, shade, shade))
self.wall_textures[wall_type] = surface.convert()
texture_cache = TextureCache()
def cast_ray(angle):
sin_a = math.sin(angle)
cos_a = math.cos(angle)
# Map dimensions
map_width = len(MAP[0])
map_height = len(MAP)
# Player's current cell
player_cell_x = int(player_x / CELL_SIZE)
player_cell_y = int(player_y / CELL_SIZE)
# Delta distances
delta_dist_x = abs(CELL_SIZE / cos_a) if cos_a != 0 else float('inf')
delta_dist_y = abs(CELL_SIZE / sin_a) if sin_a != 0 else float('inf')
# Step directions
if cos_a >= 0:
step_x = 1
side_dist_x = ((player_cell_x + 1) * CELL_SIZE - player_x) / cos_a
else:
step_x = -1
side_dist_x = (player_x - player_cell_x * CELL_SIZE) / -cos_a
if sin_a >= 0:
step_y = 1
side_dist_y = ((player_cell_y + 1) * CELL_SIZE - player_y) / sin_a
else:
step_y = -1
side_dist_y = (player_y - player_cell_y * CELL_SIZE) / -sin_a
while True:
if side_dist_x < side_dist_y:
side_dist_x += delta_dist_x
player_cell_x += step_x
side = 0 # Vertical wall
else:
side_dist_y += delta_dist_y
player_cell_y += step_y
side = 1 # Horizontal wall
# Boundary check
if 0 <= player_cell_x < map_width and 0 <= player_cell_y < map_height:
wall_type = MAP[player_cell_y][player_cell_x]
if wall_type > 0:
# Calculate distance
if side == 0:
distance = (player_cell_x * CELL_SIZE - player_x + (1 - step_x) * CELL_SIZE / 2) / cos_a
texture_pos = (player_y + distance * sin_a) % CELL_SIZE / CELL_SIZE
else:
distance = (player_cell_y * CELL_SIZE - player_y + (1 - step_y) * CELL_SIZE / 2) / sin_a
texture_pos = (player_x + distance * cos_a) % CELL_SIZE / CELL_SIZE
return distance, angle, wall_type, texture_pos
else:
# Ray is out of bounds
return MAX_DEPTH, angle, 0, 0
if distance >= MAX_DEPTH:
# Max depth reached
return MAX_DEPTH, angle, 0, 0
def draw_scene():
screen.fill(CEILING_COLOR, (0, 0, SCREEN_WIDTH, SCREEN_HEIGHT // 2))
screen.fill(FLOOR_COLOR, (0, SCREEN_HEIGHT // 2, SCREEN_WIDTH, SCREEN_HEIGHT // 2))
for x in range(NUM_RAYS):
ray_angle = (player_angle - HALF_FOV) + (x / NUM_RAYS) * FOV
distance, angle, wall_type, texture_pos = cast_ray(ray_angle)
if wall_type > 0:
distance *= math.cos(angle - player_angle) # Remove fish-eye effect
wall_height = (CELL_SIZE * SCREEN_HEIGHT) / (distance + 0.0001)
wall_top = (SCREEN_HEIGHT - wall_height) / 2
wall_bottom = wall_top + wall_height
# Get wall texture and sample the correct vertical slice
texture = texture_cache.wall_textures[wall_type]
texture_x = int(texture_pos * (TEXTURE_SIZE - 1))
column = texture.subsurface(texture_x, 0, 1, TEXTURE_SIZE)
column = pygame.transform.scale(column, (1, int(wall_height)))
# Apply fog effect
fog_factor = max(0, min(1, (MAX_DEPTH - distance) / MAX_DEPTH))
if fog_factor < 1:
column.set_alpha(int(255 * fog_factor))
screen.blit(column, (x, wall_top))
running = True
clock = pygame.time.Clock()
fps_update_timer = 0
fps_update_interval = 0.5
while running:
dt = clock.tick(60) / 1000.0 # Limit to 60 FPS and get delta time in seconds
fps_update_timer += dt
if fps_update_timer >= fps_update_interval:
fps = clock.get_fps()
pygame.display.set_caption(f'2.5D Raycaster - FPS: {int(fps)}')
fps_update_timer = 0
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
current_speed = player_speed * dt
current_rotation = rotation_speed * dt
if keys[pygame.K_LEFT]:
player_angle -= current_rotation
if keys[pygame.K_RIGHT]:
player_angle += current_rotation
sin_a = math.sin(player_angle)
cos_a = math.cos(player_angle)
if keys[pygame.K_UP]:
next_x = player_x + cos_a * current_speed
next_y = player_y + sin_a * current_speed
next_cell_x = int(next_x / CELL_SIZE)
next_cell_y = int(next_y / CELL_SIZE)
if 0 <= next_cell_x < len(MAP[0]) and 0 <= next_cell_y < len(MAP):
if MAP[next_cell_y][next_cell_x] == 0:
player_x = next_x
player_y = next_y
if keys[pygame.K_DOWN]:
next_x = player_x - cos_a * current_speed
next_y = player_y - sin_a * current_speed
next_cell_x = int(next_x / CELL_SIZE)
next_cell_y = int(next_y / CELL_SIZE)
if 0 <= next_cell_x < len(MAP[0]) and 0 <= next_cell_y < len(MAP):
if MAP[next_cell_y][next_cell_x] == 0:
player_x = next_x
player_y = next_y
draw_scene()
pygame.display.flip()
pygame.quit()
Testing
I recommend running the updated code to ensure it works as expected. The bug fixes should prevent any crashes due to index errors, and the performance should be improved with the optimizations.
Further Improvements
- Add Sprites: Implement sprite rendering for objects like enemies, pickups, etc.
- Enhance Textures: Use actual image files for textures to enhance visual quality.
- Implement Shadows: Add dynamic lighting and shadows for realism.
- Sound Effects: Incorporate sound effects for interactions.
Feel free to ask if you need assistance with any of these enhancements!