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

Re: [pygame] On walking animations...



On Wed, 7 Oct 2009 15:27:08 -0500, Guy Anderson <guy.a.anderson@xxxxxxxxx>
wrote:
> I was wondering how one could do walking animations with sprites in
pygame.
> I know that it has been done before, and it probably involves utilizing
> the
> key.pressed function in the Vector2 module, where when you press a key
the
> command retrieves a series of images for the sprite based on certain
> values
> given. I have no idea how to implement this, though, and my theory could
> be
> very wrong. All I know is that it has been done before, so I have hope.
> 
> Yeah.

The Pygame Sprites module doesn't seem to have animation (or much else)
built into it. The general idea of one way to do it is:
-Store the current action a character is performing.
-When a character starts walking, note that it's doing the "walking" action
with some direction.
-Each tick of the game, look at each sprite and set its current image to be
one of several loaded for it. Which? Refer to a dictionary of actions,
where each entry lists a numeric series of frames and how many ticks each
one should be drawn for. Maybe with other information like, "Should I start
this animation over when I reach the end?"

You'd be thinking of the sprites as characters that are doing some action,
with "what frame of animation should actually get drawn?" being secondary.

Code for part of a sprite class:

self.animations =
{"walk_east":{"sequence":[0,1,2,3],"ticks_per_frame":[1,1,1,1],"repeat":True,"animation_to_do_when_this_ends":None}
self.animation_frames = [ """List of Surface objects""" ]
self.current_animation = "walk_east"
self.position_in_anim_sequence = 0
self.current_animation_ticks_within_frame = 0
self.actual_frame_to_draw = 0

def FunctionThatGetsCalledEachTick(self):
    self.current_animation_ticks_within_frame += 1
    if self.current_animation_ticks_within_frame ==
self.animations[self.current_animation]:
        self.position_in_anim_sequence += 1
        if self.position_in_anim_sequence ==
len(self.animations[self.current_animation]["sequence"]): ## Go to next
animation or start this one over.

        ## Finally, set my actual frame drawn.
        self.actual_frame_to_draw =
self.animations[self.current_animation]["sequence"][self.position_in_anim_sequence]

Some old code of mine, at
http://kschnee.xepher.net/code/070530ShiningSeaSource.zip , has a module
called "Nixie" that handles sprites by this method. It doesn't bother to
use the built-in Sprite class, because again that class basically does
nothing.

Hope this helps!