Forum Archive

Spritesheet Animations

C0deH4cker

So this was a short project I did. It uses a PNG spritesheet downloaded from the internet to display an animation. Just a basic example of how to do this with Pythonista by using PIL.

The interesting part is actually my motivation behind writing this. Someone in a chatroom asked if Python could be used to "explode a hamster." I couldn't resist :D

Anyways, here's the Gist: https://gist.github.com/20403fcfab8cbb3bbf5a

Gcarver166

Thanks for this. It has set me on the right path for animating my characters. BTW the alpha is not correct on the image. I haven't figured out the best way to set it. I used the image converted to "L" format to set the alpha channel but that is not quite right.

C0deH4cker

I didnt need to worry about alpha though because of the black background

Gcarver166

Understood. But if anyone cares about alpha the following code inserted into hamster.py uses the 1st pixel as a keycolor to set the alpha to 0.

d = img.load()
keycolor = d[0,0]
for x in range(img.size[0]):
    for y in range(img.size[1]):
        p = d[x, y]
        if p == keycolor:
            d[x, y] = (p[0], p[1], p[2], 0)
Gcarver166

Here is another sample of an animated walking soldier.

https://gist.github.com/4180945

Dalorbi39

test @Gcarver where would the alpha code go?

Gcarver166

Right after the Image.open() call.

Dalorbi39

thanks, (dont mind me i'm an idiot)

eliskan175

How can this be used to explode a hamster?!

I love this example and I'm working on a small game engine inspired by it. I will post the code once the game engine actually works and my code isn't such a mess that my bedroom envies it.

C0deH4cker

Ill post my code for an AnimatedSprite class when I'm done with it. It will do all of the work for you. You just need to specify the filename and # of frames. Then, call the instance's draw method from your scene's draw function. There are also methods to control the animation like FPS, jump to frame, pause/play, etc

eliskan175

Hey C0deh4cker, check out the code I posted in the share section using this example.

omz

In version 1.3 (out today), spritesheet animations should be a lot easier to do. The image() function has some new, optional parameters that allow you to draw just a part of an image, without having to slice it using PIL.