Improved Collision Detection and Response
The issue you're experiencing is due to the simple collision detection and response mechanism used in the previous code. When balls move at high speeds or are large, they can "tunnel" through the hexagon or ground plane. To fix this, we'll implement more robust collision detection and response techniques.
Updated Code
import pygame
import math
import random
# Window dimensions
WIDTH, HEIGHT = 800, 600
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
HEXAGON_COLOR = (30, 144, 255) # Dodger Blue
BALL_COLOR = (255, 215, 0) # Golden Yellow
# Gravity
GRAVITY = 0.1
class Ball:
def __init__(self):
self.x = random.uniform(WIDTH // 2 - 100, WIDTH // 2 + 100)
self.y = random.uniform(HEIGHT // 2 - 100, HEIGHT // 2 + 100)
self.radius = random.randint(15, 30) # Increased radius
self.vel_x = random.uniform(-2, 2)
self.vel_y = random.uniform(-2, 0)
def update(self):
self.vel_y += GRAVITY
self.x += self.vel_x
self.y += self.vel_y
def draw(self, screen):
pygame.draw.circle(screen, BALL_COLOR, (int(self.x), int(self.y)), self.radius)
class Hexagon:
def __init__(self, x, y, size):
self.x = x
self.y = y
self.size = size
self.angle = 0
def draw(self, screen):
points = []
for i in range(6):
angle = math.radians(self.angle + i * 60)
px = self.x + math.cos(angle) * self.size
py = self.y + math.sin(angle) * self.size
points.append((px, py))
pygame.draw.polygon(screen, HEXAGON_COLOR, points, 2)
def check_collision(ball1, ball2):
dx = ball1.x - ball2.x
dy = ball1.y - ball2.y
distance = math.sqrt(dx ** 2 + dy ** 2)
if distance < ball1.radius + ball2.radius:
# Resolve collision using impulse-based method
normal_x = dx / distance
normal_y = dy / distance
tangent_x = -normal_y
tangent_y = normal_x
v1n = ball1.vel_x * normal_x + ball1.vel_y * normal_y
v1t = ball1.vel_x * tangent_x + ball1.vel_y * tangent_y
v2n = ball2.vel_x * normal_x + ball2.vel_y * normal_y
v2t = ball2.vel_x * tangent_x + ball2.vel_y * tangent_y
v1n, v2n = v2n, v1n # Swap normal velocities
ball1.vel_x = v1n * normal_x + v1t * tangent_x
ball1.vel_y = v1n * normal_y + v1t * tangent_y
ball2.vel_x = v2n * normal_x + v2t * tangent_x
ball2.vel_y = v2n * normal_y + v2t * tangent_y
# Move balls apart to prevent overlap
overlap = ball1.radius + ball2.radius - distance
ball1.x += normal_x * overlap / 2
ball1.y += normal_y * overlap / 2
ball2.x -= normal_x * overlap / 2
ball2.y -= normal_y * overlap / 2
def check_hexagon_collision(ball, hexagon):
points = []
for i in range(6):
angle = math.radians(hexagon.angle + i * 60)
px = hexagon.x + math.cos(angle) * hexagon.size
py = hexagon.y + math.sin(angle) * hexagon.size
points.append((px, py))
for i in range(6):
x1, y1 = points[i]
x2, y2 = points[(i + 1) % 6]
if line_circle_collision(x1, y1, x2, y2, ball.x, ball.y, ball.radius):
# Reflect velocity around the normal of the line
normal_x = (y2 - y1) / math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
normal_y = -(x2 - x1) / math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
dot_product = ball.vel_x * normal_x + ball.vel_y * normal_y
ball.vel_x -= 1.9 * dot_product * normal_x # Increased restitution
ball.vel_y -= 1.9 * dot_product * normal_y
# Move ball to the edge of the hexagon to prevent overlap
distance = point_line_distance(ball.x, ball.y, x1, y1, x2, y2)
if distance < ball.radius:
move_x = normal_x * (ball.radius - distance)
move_y = normal_y * (ball.radius - distance)
ball.x += move_x
ball.y += move_y
def check_ground_collision(ball):
if ball.y + ball.radius > HEIGHT:
ball.y = HEIGHT - ball.radius # Move ball to the edge of the ground
ball.vel_y *= -0.9 # Dampen bounce
ball.vel_x *= 0.99 # Friction
def line_circle_collision(x1, y1, x2, y2, cx, cy, r):
dx = x2 - x1
dy = y2 - y1
length_squared = dx ** 2 + dy ** 2
if length_squared == 0:
return False
t = max(0, min(1, ((cx - x1) * dx + (cy - y1) * dy) / length_squared))
nearest_x = x1 + t * dx
nearest_y = y1 + t * dy
distance_squared = (cx - nearest_x) ** 2 + (cy - nearest_y) ** 2
return distance_squared <= r ** 2
def point_line_distance(px, py, x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
length_squared = dx ** 2 + dy ** 2
if length_squared == 0:
return math.sqrt((px - x1) ** 2 + (py - y1) ** 2)
t = max(0, min(1, ((px - x1) * dx + (py - y1) * dy) / length_squared))
nearest_x = x1 + t * dx
nearest_y = y1 + t * dy
return math.sqrt((px - nearest_x) ** 2 + (py - nearest_y) ** 2)
def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
hexagon = Hexagon(WIDTH // 2, HEIGHT // 2, 200)
balls = [Ball() for _ in range(10)]
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill(BLACK)
hexagon.angle += 1
hexagon.draw(screen)
for ball in balls:
ball.update()
check_hexagon_collision(ball, hexagon)
check_ground_collision(ball)
# Bounce off side walls
if ball.x - ball.radius < 0:
ball.x = ball.radius
ball.vel_x *= -1
elif ball.x + ball.radius > WIDTH:
ball.x = WIDTH - ball.radius
ball.vel_x *= -1
ball.draw(screen)
for i in range(len(balls)):
for j in range(i + 1, len(balls)):
check_collision(balls[i], balls[j])
pygame.display.flip()
clock.tick(60)
pygame.quit()
if __name__ == "__main__":
main()