Jump to content
  • Advertisement
Sign in to follow this  
xhh

Pygame - sprite sheet animation

This topic is 2228 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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)

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!