Reputation: 31
My character can move and is animated when walking, and I would like to increase the speed at which it cycles through the images so as well as moving faster, it looks like she is running.
This is part of my code for the Player class. I have only included the code for the movement upwards so it isn't really long.
# Variables
walk_up = ["up1.png", "up2.png" .. etc up to "up7.png"]
image_count = len(walk_up)
frame_count = 8
walk_count = 0
class Player(pygame.sprite.Sprite):
def __init__(self, position, image):
super().__init__()
self.animg = image
self.image = load(path("Images", "Player", "Movement", self.animg)).convert_alpha()
self.rect = self.image.get_rect(topleft=position)
self.last = ""
def move(self, keypress):
global walk_count
global frame_count
x = 4
y = 4
# Reset walk_count when it gets to the max number
if walk_count >= image_count * frame_count:
walk_count = 0
if keypress[K_UP]:
self.rect.move_ip(0, -y)
self.image = walk_up[walk_count // frame_count]
display.blit(self.image, self.rect)
walk_count += 1
self.last = "up"
if keypress[K_DOWN]:
etc.
# When you stop moving the image shown is the first in the list
elif self.last != "":
if self.last == "up":
self.image = walk_up[0]
else:
walk_count = 0
If it doesn't make much sense, self.image = walk_up[walk_count // frame_count]
means that since the frame count is 8, each image will play for 8 "frames" until it switches to the next.
I am able to make the character move faster by changing the value of x and y, but when I try to add a nested function inside of "move" that checks if shift is being pressed to change the frame count (ideally that would work) I get a list index out of range error.
Upvotes: 2
Views: 52
Reputation: 210909
[...] I get a list index out of range error.
Ensure that walk_count // frame_count
is not grater or equal than the length of the list, by calculating the remainder of the division (%
-operator) between walk_count // frame_count
and len(walk_up)
:
self.image = walk_up[walk_count // frame_count]
self.image = walk_up[(walk_count // frame_count) % len(walk_up)]
Upvotes: 1