Reputation:
I have a small animation loop that cycles through images quickly. The goal is to make this constant and fluid, but I seem to be running in to an issue where the images show for a second and stay on the first frame.
The following code is from the entire player class with the animation:
class Ship(pygame.sprite.Sprite):
change_x = 0
delay = 0
frame = 1
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = PlayerShip0.convert_alpha()
self.rect = self.image.get_rect()
self.rect.x = SCREEN_X / 2 - 100
self.rect.y = SCREEN_Y - 40
def move(self, speed):
self.change_x = speed
def stop(self):
self.change_x = 0
def update(self, screen):
self.rect.x += self.change_x
if self.rect.x < 0:
self.rect.x = 0
elif self.rect.right > SCREEN_X:
self.rect.x -= 3
self.delay += 1
if self.delay >= 50:
if self.frame == 1:
self.image = PlayerShip0.convert_alpha()
self.frame = 2
self.delay = 1
if self.frame == 2:
self.image = PlayerShip1.convert_alpha()
self.frame = 3
self.delay = 1
if self.frame == 3:
self.image = PlayerShip2.convert_alpha()
self.frame = 1
self.delay = 1
print(self.frame)
screen.blit(self.image,self.rect)
Upvotes: 1
Views: 312
Reputation: 101142
Instead of
if self.frame == 1:
self.image = PlayerShip0.convert_alpha()
self.frame = 2
self.delay = 1
if self.frame == 2:
self.image = PlayerShip1.convert_alpha()
self.frame = 3
self.delay = 1
if self.frame == 3:
self.image = PlayerShip2.convert_alpha()
self.frame = 1
self.delay = 1
use
if self.frame == 1:
self.image = PlayerShip0.convert_alpha()
self.frame = 2
self.delay = 1
elif self.frame == 2:
self.image = PlayerShip1.convert_alpha()
self.frame = 3
self.delay = 1
elif self.frame == 3:
self.image = PlayerShip2.convert_alpha()
self.frame = 1
self.delay = 1
Otherwise, you set self.frame
to 2
in the first if
block, and the second if
block will set it to 3
right away, making the condition for the third if
block truthy, and so on.
Upvotes: 1