Pygame - sprite sheet animation

Started by
1 comment, last by xhh 11 years, 10 months ago
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]


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)
Advertisement
First, don't do this every frame:


self.img = pygame.Surface(self.rect.size).convert()


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:


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


And draw would need to change too:


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


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.
This worked! :) Thank you!!

This topic is closed to new replies.

Advertisement