I've been searching for some good tutorial about making simple sprite animation from few images in Python using Pygame. I still haven't found what I'm looking for.
My question is simple: how to make an animated sprite from few images (for an example: making few images of explosion with dimensions 20x20px to be as one but animated)
Any good ideas?
You could try modifying your sprite so that it swaps out its image for a different one inside
update
. That way, when the sprite is rendered, it'll look animated.Edit:
Here's a quick example I drew up:
It assumes that you have two images called
image1.png
andimage2.png
inside the same folder the code is in.There are two types of animation: frame-dependent and time-dependent. Both work in similar fashion.
Before the main loop
index
, that keeps track on the current index of the image list.current_time
orcurrent_frame
that keeps track on the current time or current frame since last the index switched.animation_time
oranimation_frames
that define how many seconds or frames should pass before switching image.During the main loop
current_time
by the amount of seconds that has passed since we last incremented it, or incrementcurrent_frame
by 1.current_time >= animation_time
orcurrent_frame >= animation_frame
. If true continue with 3-5.current_time = 0
orcurrent_frame = 0
.index = 0
.A full working example
When to chose which
Time-dependent animation allows you to play the animation at the same speed, no matter how slow/fast the frame-rate is or slow/fast your computer is. This allows your program to freely change the framerate without affecting the animation and it'll also be consistent even if the computer cannot keep up with the framerate. If the program lags the animation will catch up to the state it should've been as if no lag had happened.
Although, it might happen that the animation cycle don't synch up with the framerate, making the animation cycle seem irregular. For example, say that we have the frames updating every 0.05 second and the animation switch image every 0.075 second, then the cycle would be:
And so on...
Frame-dependent can look smoother if your computer can handle the framerate consistently. If lag happens it'll pause in its current state and restart when the lag stops, which makes the lag more noticeable. This alternative is slightly easier to implement since you just need to increment
current_frame
with 1 on each call, instead of dealing with the delta time (dt
) and passing it to every object.Sprites
Result
You should have all your sprite animations on one big "canvas", so for 3 20x20 explosion sprite frames you will have 60x20 image. Now you can get right frames by loading an area of the image.
Inside your sprite class, most likely in update method you should have something like this (hardcoded for simplicity, I prefer to have separate class to be responsible for picking the right animation frame).
self.f = 0
on__init__
.