Jump to content

  • Log In with Google      Sign In   
  • Create Account


Pygame - sprite sheet animation


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
2 replies to this topic

#1 xhh   Members   -  Reputation: 129

Like
0Likes
Like

Posted 08 June 2012 - 07:03 AM

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.

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)


Sponsor:

#2 smr   Members   -  Reputation: 1554

Like
1Likes
Like

Posted 08 June 2012 - 07:47 AM

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.

#3 xhh   Members   -  Reputation: 129

Like
0Likes
Like

Posted 08 June 2012 - 08:07 AM

This worked! :) Thank you!!




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS