How to Animate Multiple Balls Using Python

Welcome to our blog post on creating multiple bouncing balls animation using Python and the powerful data visualization library, Matplotlib. In this article, we will explore how to animate multiple balls in a two-dimensional closed rectangular box.

The art of storytelling through data visualization has gained immense popularity, and animated graphics play a vital role in conveying complex information in an engaging and understandable manner. With Matplotlib’s animation capabilities, we can easily create visually stunning and interactive ball animations that are sure to captivate your audience.

Animating Single Color Balls

Let’s understand the Python code that we will use to create a 2-D animation of multiple balls of same color and same size. The idea is to assign random velocities to each ball and let them move and collide with the walls of a two dimensional rectangular box.

First we will import the required Python libraries and modules.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from ipywidgets import Video

Specify Animation Parameters

Next, we will define a few parameters for colliding-balls animation such as the number of balls, initial positions of the balls on the canvas, and velocities of the balls.

# Set up the figure and axis
fig, ax = plt.subplots(figsize=(5,5))

# Set the x and y axis limits
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)

# Set the number of balls
n_balls = 10

# Initialize the starting x and y positions for each ball
x = np.random.rand(n_balls)
y = np.random.rand(n_balls)

# Initialize the velocity for each ball
# The velocity is a random float number
vx = np.random.randn(n_balls) * 0.05
vy = np.random.randn(n_balls) * 0.05

balls = ax.plot(x, y, 'bo')[0]

Python Update Function for Animation

In this Python function, we are basically updating the positions and direction of the velocities of each and every ball inside the 2-D box or canvas.

We are simply updating the positions of the balls by adding the value of horizontal (vx) and vertical velocity (vy) vectors to the previous positions of the balls, respectively.

To update the direction of the balls, we are first checing whether the balls are colliding with the walls of the rectangular box. If there is a collision, then reverse the direction of the horizontal and vertical velocity vectors.

# Define the update function for the animation
def update(frame):
    global x, y, vx, vy
    # Update positions
    x += vx
    y += vy

    # Check for collision with walls
    vx = np.where((x<0) | (x>1), -vx, vx)
    vy = np.where((y<0) | (y>1), -vy, vy)

    # Update data
    balls.set_data(x, y)
    return balls,

Make Animation with Matplotlib

Now we can use the matplotlib’s animation module to animate the bouncing balls.

# Create the bouncing balls animation
ani = animation.FuncAnimation(fig, update, frames=range(200), blit=True)

# Save the animation to disk
ani.save('bouncing_balls_v1.mp4', writer='ffmpeg', fps=20)

We can increase the frames from 200 to a higher number to increase the length of the animation video. We can also tinker with the ‘fps’ parameter value to change the smoothness of the moving balls in the video, but it will also affect the length of the video.

Play Balls-Animation Video

# play bouncing balls animation video
Video.from_file("bouncing_balls_v1.mp4")

Animating Multicolor Balls

To animate multiple colored balls, we can use the random module of Python and assign multiple colors to the balls. Rest of the code remains pretty much the same.

# Set up the figure and axis
fig, ax = plt.subplots(figsize=(5,5))
#ax.set_xlim(0, 1)
#ax.set_ylim(0, 1)
#ax.set_aspect('equal')

# Remove x and y ticks
ax.set_xticks([])
ax.set_yticks([])

# Set dark grey background
ax.set_facecolor('darkslategray')

# Specify number of balls 
n_balls = 10

# Initialize the starting x and y positions for each ball
x = np.random.rand(n_balls)
y = np.random.rand(n_balls)

# Initialize the velocity for each ball
# The velocity is a random float number
vx = np.random.randn(n_balls) * 0.05
vy = np.random.randn(n_balls) * 0.05

# Use different colors for the balls
colors = np.random.rand(n_balls)
balls = plt.scatter(x, y, c=colors)

def update(frame):
    global x, y, vx, vy
    # Update positions
    x += vx
    y += vy
    # Check for collision with walls
    vx = np.where((x<0) | (x>1), -vx, vx)
    vy = np.where((y<0) | (y>1), -vy, vy)
    # Update data
    balls.set_offsets(np.c_[x,y])
    return balls,

ani = animation.FuncAnimation(fig, update, frames=range(200), blit=True)

# Save the animation
ani.save('bouncing_balls_v2.mp4', writer='ffmpeg', fps=35)

Play Balls Animation Video

# play bouncing balls animation video
Video.from_file("bouncing_balls_v2.mp4")

Apart from Matplotlib, there are other Python libraries as well, like PyGame and Moviepy, that can be used for creating different types of animations. Try to explore these options as well if you are interested in programmatic animation.

Leave a Reply

Your email address will not be published. Required fields are marked *