Create a raycasting engine like doom with doom like movement and also add desnse fog and…
- User
Create a raycasting engine like doom with doom like movement and also add desnse fog and a scary setting
- Assistant
Create a raycasting engine like doom with doom like movement and also add desnse fog and a scary setting
Creating a raycasting engine similar to Doom involves several components, including rendering 3D-like environments using 2D raycasting techniques, implementing smooth and responsive player movement, adding visual effects like dense fog, and setting up a creepy or scary atmosphere through environment design and audio. Below is a comprehensive guide to help you build such an engine from scratch using Python and the Pygame library. For more performance-intensive projects, you might consider using C++ or another high-performance language, but Python is excellent for prototyping and learning.
Before you start, ensure you have the following:
Python 3.x installed on your machine.
Pygame library installed. You can install it using pip:
pip install pygame
Basic understanding of Python programming.
Familiarity with game development concepts will be beneficial but not mandatory.
Create a Project Directory: Organize your files by creating a dedicated directory for your project.
mkdir DoomRaycastingEngine
cd DoomRaycastingEngine
Initialize a Python Script: Create a main.py file where you will write your code.
touch main.py
Import Necessary Libraries: In your main.py, start by importing Pygame and other required modules.
import pygame
import math
import sys
The map is a 2D grid where each cell represents a block in the world. Empty spaces are walkable, while walls are solid.
# Define the map: 1's are walls, 0's are empty space
game_map = [
[1,1,1,1,1,1,1,1,1,1],
[1,0,0,0,1,0,0,0,0,1],
[1,0,0,0,1,0,0,0,0,1],
[1,0,0,0,1,0,0,0,0,1],
[1,0,1,1,1,1,1,1,0,1],
[1,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1],
]
MAP_WIDTH = len(game_map[0])
MAP_HEIGHT = len(game_map)
TILE_SIZE = 64 # Size of each map square
Implementing player movement involves handling keyboard inputs to move the player forward, backward, and rotate left or right.
# Player settings
player_x = TILE_SIZE * 3
player_y = TILE_SIZE * 3
player_angle = 0
player_speed = 2
rot_speed = 0.05
Raycasting involves casting rays from the player's position to determine where walls are and rendering them accordingly.
def cast_rays(screen, player_x, player_y, player_angle, textures):
num_rays = 120 # Number of rays (resolution)
fov = math.pi / 3 # 60 degrees field of view
half_fov = fov / 2
delta_angle = fov / num_rays
max_depth = 800
for ray in range(num_rays):
angle = player_angle - half_fov + ray * delta_angle
sin_a = math.sin(angle)
cos_a = math.cos(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 map_x < 0 or map_x >= MAP_WIDTH or map_y < 0 or map_y >= MAP_HEIGHT:
break
if game_map[map_y][map_x] == 1:
# Simple wall rendering based on distance
depth *= math.cos(player_angle - angle) # Remove fish-eye effect
proj_height = min(int(30000 / (depth + 0.0001)), 1000)
color = 255 / (1 + depth * depth * 0.0001)
pygame.draw.rect(screen, (color, color, color),
(ray * (SCREEN_WIDTH // num_rays),
(SCREEN_HEIGHT // 2) - proj_height // 2,
(SCREEN_WIDTH // num_rays) + 1,
proj_height))
break
To add dense fog, you can overlay a semi-transparent layer that increases in opacity with distance, obscuring faraway objects.
def apply_fog(screen, player_x, player_y, player_angle):
fog_color = (30, 30, 30) # Dark grey fog
fog_surface = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
fog_density = 200 # Higher value means denser fog
fog_surface.fill((fog_color[0], fog_color[1], fog_color[2], fog_density))
screen.blit(fog_surface, (0, 0))
Creating a scary environment involves more than just visuals. Here's how you can enhance the atmosphere:
Instead of plain colors, use textures for walls to add depth. Implement basic shading based on distance to simulate lighting.
# Placeholder for texture loading
def load_textures():
textures = {}
# Load your wall textures here
textures['wall'] = pygame.Surface((TILE_SIZE, TILE_SIZE))
textures['wall'].fill((100, 100, 100))
return textures
textures = load_textures()
# Modify render in cast_rays to use textures
# Example:
# wall_texture = textures['wall']
# screen.blit(wall_texture, (ray * (SCREEN_WIDTH // num_rays), ...))
Adding eerie sounds or background music can significantly enhance the scary atmosphere.
def load_sounds():
pygame.mixer.init()
creepy_music = pygame.mixer.Sound('creepy_music.ogg')
creepy_music.play(-1) # Loop indefinitely
return creepy_music
# Make sure to have a 'creepy_music.ogg' in your project directory
# creepy_music = load_sounds()
Fish-Eye Correction: Already handled by adjusting depth with math.cos(player_angle - angle).
Performance: Python is not the fastest language for real-time graphics. For better performance:
Textures and Shading: Implement proper texture mapping and shading to enhance visual quality.
Sprites: Add enemies or objects by rendering sprites based on their distance and angle relative to the player.
Below is a complete example incorporating the elements discussed. Note that this is a simplified version and can be expanded upon.
Textures: The current code uses plain colors for walls. To enhance the visual quality, you can load and map actual textures onto the walls. This requires calculating the exact point of intersection and adjusting the texture's x-coordinate accordingly.
Sprites: For adding enemies or objects, you'll need to implement sprite rendering based on distance and angle relative to the player’s orientation.
Dynamic Lighting: To create a more immersive and scary environment, consider implementing dynamic lighting and shadows.
Collision Detection: The current collision detection is basic. For smoother movement, you might implement more sophisticated collision handling.
Performance: Python with Pygame may not be optimal for high-performance requirements. For more complex projects, consider using C++ with SDL or other high-performance libraries.
Raycasting Tutorials:
Pygame Documentation:
Game Development Concepts:
Open Source Projects for Reference:
Sound and Music Resources:
By following this guide and expanding upon the provided example code, you can develop a simple Doom-like raycasting engine with dense fog and a scary setting. Experiment with different textures, lighting effects, and audio to enhance the atmosphere and create a more immersive and terrifying experience.
Not yet included in a published release.
import pygame
import math
import sys
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Doom-like Raycasting Engine")
# Clock
clock = pygame.time.Clock()
FPS = 60
# Define the map
game_map = [
[1,1,1,1,1,1,1,1,1,1],
[1,0,0,0,1,0,0,0,0,1],
[1,0,0,0,1,0,0,0,0,1],
[1,0,0,0,1,0,0,0,0,1],
[1,0,1,1,1,1,1,1,0,1],
[1,0,0,0,0,0,0,0,0,1],
[1,0,0,0,0,0,0,0,0,1],
[1,1,1,1,1,1,1,1,1,1],
]
MAP_WIDTH = len(game_map[0])
MAP_HEIGHT = len(game_map)
TILE_SIZE = 64
# Player settings
player_x = TILE_SIZE * 3
player_y = TILE_SIZE * 3
player_angle = 0
player_speed = 2
rot_speed = 0.05
# Load textures (placeholder)
def load_textures():
textures = {}
wall_texture = pygame.Surface((TILE_SIZE, TILE_SIZE))
wall_texture.fill((100, 100, 100))
textures['wall'] = wall_texture
return textures
textures = load_textures()
# Load sounds (optional)
def load_sounds():
pygame.mixer.init()
try:
creepy_music = pygame.mixer.Sound('creepy_music.ogg')
creepy_music.play(-1) # Loop indefinitely
return creepy_music
except:
print("No creepy_music.ogg found. Continuing without music.")
return None
creepy_music = load_sounds()
def cast_rays(screen, player_x, player_y, player_angle, textures):
num_rays = 120 # Number of rays (resolution)
fov = math.pi / 3 # 60 degrees field of view
half_fov = fov / 2
delta_angle = fov / num_rays
max_depth = 800
for ray in range(num_rays):
angle = player_angle - half_fov + ray * delta_angle
sin_a = math.sin(angle)
cos_a = math.cos(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 map_x < 0 or map_x >= MAP_WIDTH or map_y < 0 or map_y >= MAP_HEIGHT:
break
if game_map[map_y][map_x] == 1:
# Correct fish-eye effect
depth *= math.cos(player_angle - angle)
proj_height = min(int(30000 / (depth + 0.0001)), 1000)
# Simple shading based on depth
color_intensity = 255 / (1 + depth * depth * 0.0001)
color = (color_intensity, color_intensity, color_intensity)
# Calculate position and size
ray_width = SCREEN_WIDTH // num_rays
x_pos = ray * ray_width
y_pos = (SCREEN_HEIGHT // 2) - proj_height // 2
# Draw the wall slice
pygame.draw.rect(screen, color,
(x_pos, y_pos, ray_width + 1, proj_height))
break
def apply_fog(screen):
fog_color = (30, 30, 30) # Dark grey fog
fog_surface = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
fog_density = 180 # Higher value means denser fog
fog_surface.fill((fog_color[0], fog_color[1], fog_color[2], fog_density))
screen.blit(fog_surface, (0, 0))
# Main loop
running = True
while running:
clock.tick(FPS)
screen.fill((0, 0, 0)) # Clear screen with black
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Handle keys
keys = pygame.key.get_pressed()
if keys[pygame.K_ESCAPE]:
running = False
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 += player_speed * math.cos(player_angle)
player_y += player_speed * math.sin(player_angle)
# Collision detection
if game_map[int(player_y / TILE_SIZE)][int(player_x / TILE_SIZE)] == 1:
player_x -= player_speed * math.cos(player_angle)
player_y -= player_speed * math.sin(player_angle)
if keys[pygame.K_DOWN]:
player_x -= player_speed * math.cos(player_angle)
player_y -= player_speed * math.sin(player_angle)
# Collision detection
if game_map[int(player_y / TILE_SIZE)][int(player_x / TILE_SIZE)] == 1:
player_x += player_speed * math.cos(player_angle)
player_y += player_speed * math.sin(player_angle)
# Cast rays and render walls
cast_rays(screen, player_x, player_y, player_angle, textures)
# Apply fog
apply_fog(screen)
# Optional: Draw minimap
minimap_scale = 0.2
minimap = pygame.Surface((MAP_WIDTH * 10, MAP_HEIGHT * 10))
minimap.fill((50, 50, 50))
for y in range(MAP_HEIGHT):
for x in range(MAP_WIDTH):
if game_map[y][x] == 1:
pygame.draw.rect(minimap, (200, 200, 200),
(x * 10, y * 10, 10, 10))
# Draw player on minimap
pygame.draw.circle(minimap, (255, 0, 0),
(int(player_x / TILE_SIZE * 10),
int(player_y / TILE_SIZE * 10)), 3)
# Blit minimap to screen
screen.blit(minimap, (5, 5))
# Update display
pygame.display.flip()
pygame.quit()
sys.exit()