Sign in to follow this  
xhh

Pygame - sprite sheet animation

Recommended Posts

xhh    136
I can successfully take an image from a sprite sheet and blit it to the screen.
But when I try to animate it, it still shows the first image. Any help with this is much appreciated.

[attachment=9351:plat_normal.png]

[CODE]
class Plat_normal():
x = 0
y = 0
imgIndex = 0
sheet = pygame.image.load("plat_normal.png").convert_alpha()
rect = pygame.Rect((imgIndex,0),(32,32))
img = pygame.Surface(rect.size).convert()
img.blit(sheet,(0,0),rect)
def draw(self,scrn):
scrn.screen.blit(self.img, (self.x - camera.x, self.y - camera.y))
def animate(self):
self.imgIndex += 32
self.rect = pygame.Rect((self.imgIndex,0),(32,32))
self.img = pygame.Surface(self.rect.size).convert()
self.img.blit(self.sheet,(0,0),self.rect)
[/CODE]

Share this post


Link to post
Share on other sites
smr    2468
First, don't do this every frame:

[CODE]
self.img = pygame.Surface(self.rect.size).convert()
[/CODE]

You don't need to create a new backbuffer each frame. Just do it once and reuse it. If you are going to be drawing completely opaque over the entire screen each frame, then you don't even need to erase it before starting the next frame. Otherwise just clear it by drawing a filled rectangle over the entire surface.

Second, it looks like you're drawing your sprite frame to an image, then drawing that image to the screen. That's an extra step you don't need to take. You could just draw directly from your sprite sheet to the screen in your draw() method. This would turn your animate method into something like this:

[CODE]
def animate(self):
self.imgIndex += 32
self.rect = pygame.Rect((self.imgIndex,0),(32,32))
[/CODE]

And draw would need to change too:

[CODE]
def draw(self,scrn):
scrn.screen.blit(self.sheet, (self.x - camera.x, self.y - camera.y), self.rect)
[/CODE]

You have sheet as a local variable above. You'd need to stick that into your class as self.sheet. I haven't tested this code. Let me know if it helps.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this