[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] Animation (Image Strips)



Flameboy9567@xxxxxxx wrote:
Hey, I'm a new programmer and I have a question about storing images.
Since I've started using pygame, I've saved each image as its own file (ex. player_left_1.bmp)
But recently I subscribed to pygame mailing list and came across some emails discussing animation. Someone suggested using one image file with all of a character's sprites and changing the source rect. I deleted the emails before I realized their significance.
Could anyone give me an example of how this could be done? I think they used a dictionary to define animations, but I'm not sure. Any help would be very appreciated.

Here's what I did. This is part of my animation code. It assumes it's part of an object that's been loaded with a "sprite sheet" of equally-sized animation frames.


def BuildAnimationFrames(self):
"""Define a set of rectangles (Rects) representing chunks of the
sprite sheet for different animation frames. Once this is done,
you can say "switch to frame 4" and know that it's, say, "jump." """
self.animation_frames = []
for row in range(self.frames_how_many_rows):
y1 = (row * self.framesize[1]) + (row * self.frames_padding) + self.frames_outer_padding
height = self.framesize[1]
for frame in range(self.frames_per_row):
x1 = (frame * self.framesize[0]) + (frame * self.frames_padding) + self.frames_outer_padding
width = self.framesize[0]
## Drum_Roll()
self.animation_frames.append( pygame.rect.Rect(x1,y1,width,height) )
self.highest_animation_frame = len(self.animation_frames) - 1
self.SwitchToFrame(DEFAULT_SPRITE_STARTING_FRAME)


The above function doesn't touch the object's image at all. Instead it uses some parameters such as:
-frames_how_many_rows: How many animation frames per row of the image?
-frames_outer_padding: How many pixels thick is the border around the whole image?
-frames_padding: How many pixels between frames? (ie. are there borders around the animation frames for easy visibility?)


This function uses those params to build a set of rectangles defining what parts of the image contain each animation frame. Then you can draw the sprite by referring to the image using the rectangle of your choice (in self.animation_frames).

Kris