Chapter 17. Sprites and Collision Detection

 

In this chapter, we’ll continue using Pygame to do animation. We’ll look at things called sprites, which help us keep track of lots of images moving on the screen. We’ll also see how to detect when two images overlap or hit each other, like when a ball hits a paddle or a spaceship hits an asteroid.

Sprites

In the last chapter, you saw that simple animation isn’t quite so simple after all. If you have a lot of images and are moving them around, it can be a lot of work keeping track of what’s “under” each image so you can repaint when you move the image. In our first example with the beach ball, the background was just white, so it was easier. But you can imagine that, with graphics in the background, it would get more complicated.

Fortunately, Pygame has some extra help for us. The individual images or parts of an image that move around are called sprites, and Pygame has a special module for handling sprites. This lets us move graphical objects around more easily.

In the last chapter, we had a beach ball bouncing around the screen. What if we want a whole bunch of beach balls bouncing around? We could write the code to manage each ball individually, but instead we’re going to use Pygame’s sprite module to make things easier.

Bump! Collision detection

 

Counting time

 

What did you learn?

 
 
 

Test your knowledge

 
 
 

Try it out

 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest