I'll help you create a simple 2D raycasting program that uses machine learning to predict collision points. This example will use a basic neural network to learn patterns in ray collision data.
python
import numpy as np
from sklearn.neural_network import MLPRegressor
import pygame
import math
class RaycastEnvironment:
def __init__(self, width=800, height=600):
pygame.init()
self.width = width
self.height = height
self.screen = pygame.display.set_mode((width, height))
self.obstacles = [
pygame.Rect(300, 200, 100, 100),
pygame.Rect(500, 400, 80, 80),
pygame.Rect(100, 400, 120, 60)
]
def cast_ray(self, origin, angle):
ray_dir = (math.cos(angle), math.sin(angle))
closest_hit = None
min_dist = float('inf')
for obstacle in self.obstacles:
# Check intersection with each obstacle edge
edges = [
(obstacle.topleft, obstacle.topright),
(obstacle.topright, obstacle.bottomright),
(obstacle.bottomright, obstacle.bottomleft),
(obstacle.bottomleft, obstacle.topleft)
]
for edge in edges:
hit = self.line_intersection(origin, ray_dir, edge[0], edge[1])
if hit:
dist = math.sqrt((hit[0] - origin[0])**2 + (hit[1] - origin[1])**2)
if dist < min_dist:
min_dist = dist
closest_hit = hit
return closest_hit if closest_hit else (origin[0] + ray_dir[0] * 1000,
origin[1] + ray_dir[1] * 1000)
def line_intersection(self, ray_origin, ray_dir, point1, point2):
x1, y1 = ray_origin
x2, y2 = x1 + ray_dir[0], y1 + ray_dir[1]
x3, y3 = point1
x4, y4 = point2
den = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
if den == 0:
return None
t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / den
u = -((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / den
if 0 <= u <= 1 and t > 0:
return (x1 + t * (x2 - x1), y1 + t * (y2 - y1))
return None
class RaycastML:
def __init__(self):
self.model = MLPRegressor(hidden_layer_sizes=(10, 10), max_iter=1000)
self.env = RaycastEnvironment()
def generate_training_data(self, n_samples=1000):
X = [] # Input features: ray origin (x, y) and angle
y = [] # Output: collision point (x, y)
for _ in range(n_samples):
origin = (np.random.randint(0, self.env.width),
np.random.randint(0, self.env.height))
angle = np.random.uniform(0, 2 * math.pi)
collision = self.env.cast_ray(origin, angle)
X.append([origin[0], origin[1], angle])
y.append([collision[0], collision[1]])
return np.array(X), np.array(y)
def train(self):
X, y = self.generate_training_data()
self.model.fit(X, y)
def run_simulation(self):
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
self.env.screen.fill((0, 0, 0))
# Draw obstacles
for obstacle in self.env.obstacles:
pygame.draw.rect(self.env.screen, (255, 255, 255), obstacle)
# Get mouse position and cast rays
mouse_pos = pygame.mouse.get_pos()
for angle in np.linspace(0, 2 * math.pi, 36):
# Real raycast
collision = self.env.cast_ray(mouse_pos, angle)
pygame.draw.line(self.env.screen, (0, 255, 0), mouse_pos, collision)
# ML prediction
prediction = self.model.predict([[mouse_pos[0], mouse_pos[1], angle]])
pygame.draw.line(self.env.screen, (255, 0, 0), mouse_pos, prediction[0], 1)
pygame.display.flip()
clock.tick(60)
pygame.quit()
if __name__ == "__main__":
ml_raycast = RaycastML()
ml_raycast.train()
ml_raycast.run_simulation()
This program combines:
Raycasting physics simulation
Machine learning using scikit-learn's MLPRegressor
Visual representation using Pygame
The program creates a window where:
White rectangles represent obstacles
Green lines show actual raycasts
Red lines show ML-predicted ray collisions
Rays originate from the mouse cursor position
To run this, you'll need these dependencies:
bash
pip install numpy sklearn pygame
The neural network tries to learn to predict ray collision points based on the ray's origin position and angle. You'll see both the actual raycasts (green) and the ML predictions (red) simultaneously, allowing you to compare their accuracy.
Would you like me to explain any particular part in more detail?