Okay, let's create a Python program using pygame to simulate a ball bouncing inside a hexagon that is also spinning.
We'll need:
Pygame setup: Initialize the window, clock, etc.
Ball class: To manage the ball's position, velocity, radius, and drawing.
Hexagon class: To manage the hexagon's center, size, angle, angular velocity, calculate its vertices, and draw it.
Collision detection: A function or method to check if the ball collides with any of the hexagon's sides.
Collision response: How the ball's velocity changes when it hits a wall.
Simulation loop: Update positions, check collisions, and redraw everything.
python
import pygame
import math
import sys
# --- Constants ---
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 60
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
# --- Vector Math Helper (using pygame.math.Vector2) ---
# Pygame provides a Vector2 class which is very useful for physics simulations
# No need to create our own unless specifically required.
# --- Ball Class ---
class Ball:
def __init__(self, x, y, radius, color, speed_x, speed_y):
self.pos = pygame.math.Vector2(x, y)
self.radius = radius
self.color = color
self.velocity = pygame.math.Vector2(speed_x, speed_y)
def update(self):
self.pos += self.velocity
def draw(self, screen):
pygame.draw.circle(screen, self.color, (int(self.pos.x), int(self.pos.y)), self.radius)
# --- Hexagon Class ---
class Hexagon:
def __init__(self, center_x, center_y, side_length, color, angular_velocity_deg_per_sec):
self.center = pygame.math.Vector2(center_x, center_y)
self.side_length = side_length
self.color = color
self.angle = 0 # Angle in radians
self.angular_velocity = math.radians(angular_velocity_deg_per_sec) / FPS # Convert to radians per frame
def update(self):
self.angle += self.angular_velocity
# Optional: Keep angle within 0 to 2*pi
# self.angle %= (2 * math.pi)
def get_vertices(self):
vertices = []
# A regular hexagon's vertices are distance 'side_length' from the center
# and are spaced 60 degrees (pi/3 radians) apart.
# Starting angle ensures one vertex is on the positive x-axis relative to center when angle=0
# We'll start with a flat top/bottom, so vertices are at angles 30, 90, 150, 210, 270, 330 degrees
# which is pi/6, pi/2, 5pi/6, 7pi/6, 3pi/2, 11pi/6 radians relative to positive x-axis.
# We add the current rotation angle to these initial angles.
initial_angles = [math.pi / 6 + i * math.pi / 3 for i in range(6)]
for initial_angle in initial_angles:
# Calculate angle including current rotation
current_angle = initial_angle + self.angle
# Convert polar coordinates (distance, angle) to Cartesian (x, y)
x = self.center.x + self.side_length * math.cos(current_angle)
y = self.center.y + self.side_length * math.sin(current_angle)
vertices.append((int(x), int(y))) # Pygame draw functions expect integer coordinates
return vertices
def get_sides(self):
vertices = self.get_vertices()
sides = []
for i in range(6):
# A side is a line segment from vertex i to vertex (i+1) % 6
sides.append((pygame.math.Vector2(vertices[i]), pygame.math.Vector2(vertices[(i + 1) % 6])))
return sides
def draw(self, screen):
vertices = self.get_vertices()
if len(vertices) > 1:
pygame.draw.polygon(screen, self.color, vertices, 2) # Draw as lines (thickness 2)
# --- Collision Detection and Response ---
def closest_point_on_segment(point, p1, p2):
"""
Finds the closest point on a line segment (p1, p2) to a given point.
Returns the closest point and the square of the distance.
"""
line_vec = p2 - p1
point_vec = point - p1
line_len_sq = line_vec.length_squared()
if line_len_sq == 0: # p1 and p2 are the same point
return p1, point_vec.length_squared()
# Project point_vec onto line_vec
t = point_vec.dot(line_vec) / line_len_sq
t = max(0.0, min(1.0, t)) # Clamp t to [0, 1] to stay within the segment
closest = p1 + t * line_vec
distance_sq = (point - closest).length_squared()
return closest, distance_sq
def check_collision(ball, hexagon):
sides = hexagon.get_sides()
collided = False
for p1, p2 in sides:
closest, dist_sq = closest_point_on_segment(ball.pos, p1, p2)
if dist_sq < ball.radius**2:
collided = True
distance = math.sqrt(dist_sq)
# --- Collision Response ---
# Calculate the normal vector of the wall at the collision point
# The normal points from the closest point on the segment to the ball center
normal = ball.pos - closest
if normal.length() == 0: # Handle edge case where ball center is exactly on the segment
# This is unlikely with floating point numbers, but good practice.
# Just pick an arbitrary normal direction (e.g., based on segment orientation)
segment_vector = p2 - p1
normal = pygame.math.Vector2(-segment_vector.y, segment_vector.x).normalize()
else:
normal = normal.normalize()
# Move the ball out of penetration
# Push out distance is radius - actual distance
push_out_distance = ball.radius - distance
if push_out_distance > 0:
ball.pos += normal * push_out_distance
# Reflect the velocity
# Reflection formula: v_prime = v - 2 * (v . n) * n
dot_product = ball.velocity.dot(normal)
# Only reflect if moving towards the wall (dot product is negative)
# This avoids double reflection if the ball somehow gets inside and is moving away
if dot_product < 0:
ball.velocity = ball.velocity - 2 * dot_product * normal
# Optional: Add a small friction or damping
# ball.velocity *= 0.99
return collided # We return if *any* collision occurred in this step (though response is per segment)
# --- Main Game Loop ---
def main():
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Spinning Hexagon Ball Simulation")
clock = pygame.time.Clock()
# Create game objects
ball = Ball(SCREEN_WIDTH // 2 + 50, SCREEN_HEIGHT // 2, 10, RED, 200/FPS, 150/FPS) # speeds in pixels per frame
hexagon = Hexagon(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2, 150, BLUE, 30) # 30 degrees per second
running = True
while running:
# --- Event Handling ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# You could add controls here, e.g., pause, reset, change speeds
# --- Update Game State ---
ball.update()
hexagon.update()
check_collision(ball, hexagon) # Check and resolve collisions
# --- Drawing ---
screen.fill(BLACK) # Background
hexagon.draw(screen)
ball.draw(screen)
# --- Update Display ---
pygame.display.flip()
# --- Cap Frame Rate ---
clock.tick(FPS)
pygame.quit()
sys.exit()
# --- Run the game ---
if __name__ == "__main__":
main()
Explanation:
Pygame Setup: Basic initialization, screen creation, caption, and a clock to control the frame rate.
Constants: Define screen dimensions, colors, and FPS for readability.
Ball Class:
Holds pos (a Vector2), radius, color, and velocity (also a Vector2).
update(): Moves the ball by adding the velocity vector to the position vector.
draw(): Draws a circle on the screen.
Hexagon Class:
Holds center (a Vector2), side_length, color, angle (current rotation), and angular_velocity.
angular_velocity is converted from degrees per second to radians per frame based on the FPS.
update(): Increments the angle by the angular_velocity.
get_vertices(): Calculates the (x, y) coordinates of the 6 vertices for the current angle. It uses trigonometry (cos, sin) and the radius (which is equal to the side length for a regular hexagon rotated this way). It starts with initial angles appropriate for a hexagon with a flat top/bottom when angle=0.
get_sides(): Returns a list of line segments (pairs of Vector2) representing each side of the hexagon based on the current vertices.
draw(): Gets the current vertices and draws a polygon (outline) using pygame.draw.polygon.
closest_point_on_segment(point, p1, p2) Function:
This is a standard geometric function. Given a point and a line segment (defined by its endpoints p1 and p2), it finds the point on the segment that is closest to the given point.
It works by projecting the vector from p1 to point onto the vector from p1 to p2. The projection ratio t determines where along the line the closest point lies. Clamping t to [0, 1] ensures the closest point is on the segment, not just on the infinite line.
To run this code:
Make sure you have pygame installed (pip install pygame).
Save the code as a Python file (e.g., spinning_hexagon.py).
Run it from your terminal: python spinning_hexagon.py
It returns the closest point (Vector2) and the square of the distance (to avoid sqrt until the final check).
check_collision(ball, hexagon) Function:
Gets the current sides of the rotating hexagon.
Iterates through each side (p1, p2).
For each side, it calls closest_point_on_segment to find the closest point on the side to the ball's center.
If the distance from the ball's center to this closest point is less than the ball's radius, a collision is detected with this specific side.
Collision Response:
Calculate the normal vector: This vector points from the closest point on the wall towards the ball's center. Normalizing it gives a unit vector n perpendicular to the wall at the collision point.
Push-out: If the ball has penetrated the wall (distance < radius), it moves the ball slightly along the normal vector to get it just outside the wall. This prevents sticking or getting trapped.
Reflection: It uses the reflection formula v_prime = v - 2 * (v . n) * n to calculate the new velocity after bouncing. The dot product v . n tells us how much of the velocity is in the direction of the normal. Multiplying by 2*n and subtracting it from the original velocity effectively reverses the component of velocity perpendicular to the wall while leaving the component parallel to the wall unchanged.
It only applies the reflection if the ball is moving towards the wall (v.dot(n) < 0) to avoid weird behavior if the push-out puts the ball slightly "inside" and it reflects again immediately.
Main Loop:
Initializes pygame, creates the Ball and Hexagon objects.
The while running: loop is the heart of the simulation.
Events: Checks for the quit event (pygame.QUIT).
Update: Calls update() for both the ball and the hexagon.
Collision: Calls check_collision() to handle bouncing.
Drawing: Fills the background, then draws the hexagon and the ball.
Display Update:pygame.display.flip() makes everything drawn visible on the screen.
Clock:clock.tick(FPS) pauses the loop to maintain the desired frame rate.
Run Check:if __name__ == "__main__": main() ensures the main() function runs when the script is executed directly.