Here's a Python program using Pygame that simulates a ball bouncing inside a spinning hexagon. The program creates a visual representation with collision detection and rotation:
import pygame
import math
import random
# Initialize Pygame
pygame.init()
# Set up the display
WIDTH = 800
HEIGHT = 800
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Ball in Spinning Hexagon")
# Colors
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLACK = (0, 0, 0)
# Hexagon properties
HEXAGON_RADIUS = 300
HEXAGON_CENTER = (WIDTH // 2, HEIGHT // 2)
rotation_angle = 0
rotation_speed = 0.5 # degrees per frame
# Ball properties
BALL_RADIUS = 20
ball_pos = [WIDTH // 2, HEIGHT // 2]
ball_speed = [random.uniform(-5, 5), random.uniform(-5, 5)]
# Function to create hexagon vertices
def get_hexagon_vertices(center, radius, angle):
vertices = []
for i in range(6):
vertex_angle = math.radians(60 * i + angle)
x = center[0] + radius * math.cos(vertex_angle)
y = center[1] + radius * math.sin(vertex_angle)
vertices.append((x, y))
return vertices
# Function to check collision between ball and line segment
def line_circle_collision(ball_pos, ball_radius, line_start, line_end):
# Vector from line start to ball center
line_vec = (line_end[0] - line_start[0], line_end[1] - line_start[1])
ball_vec = (ball_pos[0] - line_start[0], ball_pos[1] - line_start[1])
# Project ball_vec onto line_vec
line_len_sq = line_vec[0]**2 + line_vec[1]**2
if line_len_sq == 0:
return False, None
t = max(0, min(1, (ball_vec[0] * line_vec[0] + ball_vec[1] * line_vec[1]) / line_len_sq))
# Find closest point on line to ball center
closest_x = line_start[0] + t * line_vec[0]
closest_y = line_start[1] + t * line_vec[1]
# Distance from ball center to closest point
dist_sq = (ball_pos[0] - closest_x)**2 + (ball_pos[1] - closest_y)**2
if dist_sq <= ball_radius**2:
# Calculate normal vector
dx = ball_pos[0] - closest_x
dy = ball_pos[1] - closest_y
dist = math.sqrt(dist_sq)
if dist == 0:
return False, None
normal = (dx/dist, dy/dist)
return True, normal
return False, None
# Function to reflect velocity vector
def reflect_velocity(velocity, normal):
dot_product = velocity[0] * normal[0] + velocity[1] * normal[1]
return [
velocity[0] - 2 * dot_product * normal[0],
velocity[1] - 2 * dot_product * normal[1]
]
# Game loop
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Update rotation
rotation_angle += rotation_speed
if rotation_angle >= 360:
rotation_angle -= 360
# Get current hexagon vertices
vertices = get_hexagon_vertices(HEXAGON_CENTER, HEXAGON_RADIUS, rotation_angle)
# Update ball position
ball_pos[0] += ball_speed[0]
ball_pos[1] += ball_speed[1]
# Check collisions with hexagon walls
for i in range(6):
start_vertex = vertices[i]
end_vertex = vertices[(i + 1) % 6]
collision, normal = line_circle_collision(ball_pos, BALL_RADIUS, start_vertex, end_vertex)
if collision:
# Reflect ball velocity
ball_speed = reflect_velocity(ball_speed, normal)
# Move ball out of collision
overlap = BALL_RADIUS - math.sqrt((ball_pos[0] - (start_vertex[0] + end_vertex[0])/2)**2 +
(ball_pos[1] - (start_vertex[1] + end_vertex[1])/2)**2 +
HEXAGON_RADIUS**2)
if overlap > 0:
ball_pos[0] += normal[0] * overlap
ball_pos[1] += normal[1] * overlap
# Clear screen
screen.fill(BLACK)
# Draw hexagon
pygame.draw.polygon(screen, WHITE, vertices, 2)
# Draw ball
pygame.draw.circle(screen, RED, (int(ball_pos[0]), int(ball_pos[1])), BALL_RADIUS)
# Update display
pygame.display.flip()
# Control frame rate
clock.tick(60)
pygame.quit()
This program does the following:
-
Sets up a Pygame window and initializes basic properties for the hexagon and ball.
-
Creates a rotating hexagon using the get_hexagon_vertices function, which calculates the vertices based on the current rotation angle.
-
Implements a ball with random initial velocity that moves within the hexagon.
-
Includes collision detection between the ball and hexagon walls using the line_circle_collision function, which:
- Checks if the ball intersects with any hexagon side
- Returns the normal vector of the collision surface if there is a collision
-
Implements velocity reflection using the reflect_velocity function when the ball hits a wall.
-
Handles the main game loop, which:
- Updates the rotation of the hexagon
- Updates the ball's position
- Checks for collisions
- Draws everything to the screen
To run this program, you'll need to have Pygame installed. You can install it using pip:
pip install pygame
Features of the simulation:
- The hexagon rotates continuously
- The ball bounces realistically off the walls
- The ball maintains its speed after collisions (perfectly elastic collisions)
- The collision detection handles the rotating walls correctly
You can modify various parameters to change the behavior:
HEXAGON_RADIUS: Change the size of the hexagon
rotation_speed: Change how fast the hexagon rotates
BALL_RADIUS: Change the size of the ball
ball_speed: Change the initial speed of the ball
The program will continue running until you close the window. The ball will stay contained within the rotating hexagon, bouncing off the walls as it moves.