The delay and frame-by-frame sluggishness in your animation are primarily due to the event-driven simulation approach you're using. In an event-driven simulation, only one event (such as a collision) is processed per animation frame. This can result in noticeable delays and less smooth animations, especially when multiple events need to be processed within the timeframe of a single frame.
To achieve a smoother and more responsive animation, consider switching to a time-step-based simulation. In this approach, the simulation progresses in fixed increments of time (dt), updating the positions and velocities of all particles at each step. This method is generally more compatible with real-time animations and can provide smoother visuals.
Here's how you can modify your code to implement a time-step-based simulation:
1. Modify the Simulation Loop
Instead of processing one event per frame, update all particle positions based on a fixed time step. Handle collisions within each time step by checking for overlaps and resolving them accordingly.
2. Update the simulate Function
Refactor the simulate function to advance the simulation by a fixed dt and handle any collisions that occur within that time frame.
3. Optimize Collision Detection
Use more efficient collision detection algorithms to handle particle interactions, reducing computational overhead.
4. Update the Animation Interval
Set the animation interval (delta_t) to a value that corresponds to real-time frame rates (e.g., 30 or 60 frames per second).
Revised Code Example
Below is a revised version of your code implementing a time-step-based simulation. This should result in a smoother and more responsive animation:
import math
import random
import warnings
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Disable warnings
warnings.filterwarnings("ignore")
# Matplotlib configuration
x_lim = (0, 30)
y_lim = (0, 20)
PLT_RADIUS_SCALER = 25
# Set up plot to draw animations
fig, ax = plt.subplots()
ax.set_xlim(x_lim)
ax.set_ylim(y_lim)
ax.set_xticks([])
ax.set_yticks([])
class Particle:
def __init__(self, rx, ry, vx, vy, radius, mass):
self.rx = rx
self.ry = ry
self.vx = vx
self.vy = vy
self.radius = radius
self.mass = mass
self.scatter = ax.scatter(self.rx, self.ry, s=self.radius * PLT_RADIUS_SCALER * 10, edgecolors='k')
def move(self, dt):
self.rx += self.vx * dt
self.ry += self.vy * dt
self.scatter.set_offsets([self.rx, self.ry])
def check_wall_collisions(self, x_lim, y_lim):
collided = False
# Check vertical walls
if self.rx - self.radius < x_lim[0]:
self.rx = x_lim[0] + self.radius
self.vx = -self.vx
collided = True
elif self.rx + self.radius > x_lim[1]:
self.rx = x_lim[1] - self.radius
self.vx = -self.vx
collided = True
# Check horizontal walls
if self.ry - self.radius < y_lim[0]:
self.ry = y_lim[0] + self.radius
self.vy = -self.vy
collided = True
elif self.ry + self.radius > y_lim[1]:
self.ry = y_lim[1] - self.radius
self.vy = -self.vy
collided = True
if collided:
self.update_position()
def update_position(self):
self.scatter.set_offsets([self.rx, self.ry])
def detect_and_resolve_collision(p1, p2):
dx = p2.rx - p1.rx
dy = p2.ry - p1.ry
distance = math.hypot(dx, dy)
if distance < p1.radius + p2.radius:
# Overlap detected, resolve the collision
overlap = 0.5 * (p1.radius + p2.radius - distance + 1e-6)
angle = math.atan2(dy, dx)
p1.rx -= overlap * math.cos(angle)
p1.ry -= overlap * math.sin(angle)
p2.rx += overlap * math.cos(angle)
p2.ry += overlap * math.sin(angle)
# Update velocities
dvx = p2.vx - p1.vx
dvy = p2.vy - p1.vy
vn = dvx * math.cos(angle) + dvy * math.sin(angle)
if vn > 0:
return # They are moving away from each other
# Compute impulse
impulse = (2 * vn) / (p1.mass + p2.mass)
p1.vx += impulse * p2.mass * math.cos(angle)
p1.vy += impulse * p2.mass * math.sin(angle)
p2.vx -= impulse * p1.mass * math.cos(angle)
p2.vy -= impulse * p1.mass * math.sin(angle)
def initialize_particles(n_balls):
balls = []
attempts = 0
max_attempts = 1000
while len(balls) < n_balls and attempts < max_attempts:
x = random.uniform(x_lim[0] + 2.5, x_lim[1] - 2.5)
y = random.uniform(y_lim[0] + 2.5, y_lim[1] - 2.5)
vx = random.uniform(-5, 5)
vy = random.uniform(-5, 5)
mass = random.uniform(0.5, 1.5)
radius = random.uniform(2.2, 2.5)
new_particle = Particle(x, y, vx, vy, radius, mass)
# Ensure no overlap with existing particles
overlap = False
for p in balls:
distance = math.hypot(new_particle.rx - p.rx, new_particle.ry - p.ry)
if distance < new_particle.radius + p.radius:
overlap = True
break
if not overlap:
balls.append(new_particle)
else:
new_particle.scatter.remove() # Remove the scatter if overlapping
attempts += 1
if attempts == max_attempts:
print("Max attempts reached. Some particles may not have been created.")
return balls
# Initialize particles
n_balls = 10 # Increase or decrease as needed
balls = initialize_particles(n_balls)
# Simulation parameters
dt = 0.02 # seconds per frame (50 FPS)
simulation_limit = 100.0 # Total simulation time in seconds
current_time = 0.0
def simulate_step():
global current_time
# Move all particles
for ball in balls:
ball.move(dt)
ball.check_wall_collisions(x_lim, y_lim)
# Check for collisions between particles
for i in range(len(balls)):
for j in range(i + 1, len(balls)):
detect_and_resolve_collision(balls[i], balls[j])
current_time += dt
def animate(frame):
simulate_step()
return [ball.scatter for ball in balls]
# Set animation interval to match the dt (in milliseconds)
animation_interval = dt * 1000 # Convert seconds to milliseconds
ani = animation.FuncAnimation(
fig, animate, frames=int(simulation_limit / dt),
interval=animation_interval, blit=True, repeat=False
)
plt.show()
Key Changes Explained
-
Time-Step-Based Simulation:
- The simulation advances in fixed time steps (
dt = 0.02 seconds), which corresponds to 50 frames per second. This ensures a smooth and consistent animation.
-
Collision Detection and Resolution:
- Collisions between particles are detected by checking the distance between them. If a collision is detected (overlap), the particles are repositioned to eliminate the overlap, and their velocities are updated based on conservation of momentum.
- Collisions with walls are handled by reversing the velocity component perpendicular to the wall and ensuring particles remain within bounds.
-
Initialization Without Overlaps:
- The
initialize_particles function ensures that particles are placed without overlapping. If an overlap is detected during initialization, the particle is not added, and an attempt is made to place it again until the maximum number of attempts is reached.
-
Optimized Animation:
- By using
blit=True and returning only the updated scatter plots, the animation becomes more efficient.
- The
simulate_step function updates all particle positions and handles all necessary collisions within each frame, ensuring that the animation remains smooth.
-
Adjustable Parameters:
- You can adjust
n_balls, dt, and simulation_limit to control the number of particles, the simulation's time resolution, and the total simulation time, respectively.
Additional Tips
By adopting a time-step-based approach and optimizing collision handling, your animation should become significantly smoother and more responsive, eliminating the delays and frame-by-frame lag you experienced with the event-driven method.