How to animate an image in Pygame

One of the thing you want to do often, when making a game, is animate an object.download-bttn

We are going to learn how to move a red square image across the pygame window. Here’s an animation of the finished product:

 

red square

The full code is at the below. download-bttnDownload Source Code

Scroll down for a line by line of the important parts

Let’s look at some important lines

Line 8 :

redSquare = pygame.image.load("images/red-square.png").convert()

This line loads an image  (read more here)

Line  9fpsClock = pygame.time.Clock()

This line grabs a reference to Pygame’s clock which we’ll store in a variable called fpsClock (which we’ll use to control the animation framework — see line  25)

Lines 15-17

These lines are where all the action is .

Line 15 : updates the x coordinate (well, the variable that we’ll use for the x coordinate of the image

Line 16 : clear surface so that it’s blank

Line 17 : blit the image to the screen at the new x (imageX)

Want to see what this program would look like without line 16 (clearing canvas)?

Here you go :

 

animation-of-square-no-canvas-clearing
Removing line 16 –canvas not cleared

 

Without line 16, we keep painting or blitting the red square onto the  surface so , as you can see, instead of our intended goal of having the square more left, what happens is that we pain the square left and then when paint the square again to the left so the image just appears to expand leftwards.

LIne 25 : controls the effective frame rate

Let’s see what would happen if we changed the 30 to a 3 so that the line now becomes

Here’s the animation (Recorded at the same speed btw)

decrease-fps

 

As you can see the frame rate has drastically decreased