To create a 2D particle simulator with the specified requirements, follow these steps:
Step-by-Step Explanation
-
Setup the Environment:
- Use Pygame for visualization.
- Define constants for the container size and particle radius.
-
Particle Class:
- Each particle has position (x, y), velocity (vx, vy), and radius.
- Initialize particles with random positions and velocities.
-
Wall Collisions:
- After moving particles, check if they hit the walls. Reverse the velocity component perpendicular to the wall and adjust their position to the wall's edge.
-
Particle Collisions:
- For each pair of particles, check if they are within collision distance (sum of radii).
- If they collide, resolve the collision by adjusting their velocities using elastic collision formulas and separating their positions to prevent overlap.
-
Simulation Loop:
- Continuously update particle positions, handle collisions, and redraw the particles on the screen.
Code Implementation
import pygame
import random
import math
WIDTH, HEIGHT = 800, 800
RADIUS = 2.5 # 5 pixels diameter
class Particle:
def __init__(self):
self.x = random.uniform(RADIUS, WIDTH - RADIUS)
self.y = random.uniform(RADIUS, HEIGHT - RADIUS)
angle = random.uniform(0, 2 * math.pi)
speed = random.uniform(1, 5)
self.vx = speed * math.cos(angle)
self.vy = speed * math.sin(angle)
def update(self):
# Update position
self.x += self.vx
self.y += self.vy
# Handle wall collisions
if self.x - RADIUS < 0:
self.x = RADIUS
self.vx *= -1
elif self.x + RADIUS > WIDTH:
self.x = WIDTH - RADIUS
self.vx *= -1
if self.y - RADIUS < 0:
self.y = RADIUS
self.vy *= -1
elif self.y + RADIUS > HEIGHT:
self.y = HEIGHT - RADIUS
self.vy *= -1
def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
particles = [Particle() for _ in range(100)]
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((0, 0, 0))
# Update all particles
for p in particles:
p.update()
# Handle particle-particle collisions
for i in range(len(particles)):
for j in range(i + 1, len(particles)):
p1 = particles[i]
p2 = particles[j]
dx = p1.x - p2.x
dy = p1.y - p2.y
dist_sq = dx**2 + dy**2
if dist_sq < (2 * RADIUS)**2 and dist_sq > 0: # Avoid division by zero
dist = math.sqrt(dist_sq)
nx = dx / dist
ny = dy / dist
overlap = (2 * RADIUS - dist)
# Move particles apart
p1.x += nx * overlap / 2
p1.y += ny * overlap / 2
p2.x -= nx * overlap / 2
p2.y -= ny * overlap / 2
# Calculate velocity change
dvx = p1.vx - p2.vx
dvy = p1.vy - p2.vy
dot = dvx * nx + dvy * ny
# Update velocities
p1.vx -= dot * nx
p1.vy -= dot * ny
p2.vx += dot * nx
p2.vy += dot * ny
# Draw particles
for p in particles:
pygame.draw.circle(screen, (255, 255, 255), (int(p.x), int(p.y)), int(RADIUS))
pygame.display.flip()
pygame.quit()
if __name__ == "__main__":
main()
Explanation of Key Parts
- Initialization: Particles are placed randomly within the container, avoiding initial overlap with walls.
- Movement and Wall Handling: Each particle's position is updated, and walls are checked using simple boundary conditions.
- Collision Detection and Resolution: For each particle pair, check if they are within collision distance. If so, resolve the collision by adjusting velocities using elastic collision physics and separating their positions to prevent overlap.
- Visualization: Pygame is used to draw particles on the screen, providing a real-time view of the simulation.
This code creates a dynamic 2D particle system where particles move, bounce off walls, and collide with each other realistically, mimicking billiard ball physics.