Reputation: 111
Hey guys I have some issues while I was making my game.... I want to move my character while the image changes every "step" that it looks like an animation...
I haven been working on this for hours but the only thing I have done so far is to move the char but all images are drawn at once while moving
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
currentimageleft = 1
gamedisplay.blit(background, (0,0))
if currentimageleft == 1:
gamedisplay.blit(temp1, (template_x, template_y), (g1x, g1y, box, box))
template_x -= moveit
currentimageleft += 1
if currentimageleft == 2:
gamedisplay.blit(temp1, (template_x, template_y), (g2x, g2y, box, box))
template_x -= moveit
currentimageleft += 1
if currentimageleft == 3:
gamedisplay.blit(temp1, (template_x, template_y), (g3x, g3y, box, box))
template_x -= moveit
currentimageleft += 1
if currentimageleft == 4:
gamedisplay.blit(temp1, (template_x, template_y), (g4x, g4y, box, box))
template_x -= moveit
currentimageleft = 1
pygame.display.update()
Upvotes: 0
Views: 40
Reputation: 155
Since you are incrementing currentimgeleft
in each of your if
blocks, it then triggers the next if
block down the line. You only want one to trigger each frame, so switch the if
to elif
for all but the first one and then you'll have only one triggering each time the K_LEFT
button is pressed on the keyboard. Like so
if currentimageleft == 1:
# code
elif currentimageleft == 2:
# code
...
However, notice that you are setting currentimageleft
each time you enter the bigger if
statement for the keypress. This will ensure that you always end up using the very first sprite of your animation. You may want to associate currentimageleft
with a class variable by declaring it in __init__
to be something like
def __init__(self, ...):
# other code, including possible parent constructors
self.currentleftimage = 1
# more code
You would then access your variable with self.currentimageleft
instead of currentimageleft
. This would then allow you to use else
or elif
clauses on your button press detection (the outer if
in your code snippet) to reset the self.currentleftimage
variable back to 1
allowing you to track motion that way instead.
You may also find this other answer on the equivalent form of switch
in Python interesting, though several calls to elif
clauses is also perfectly normal and may lead to more legible code in many cases.
Upvotes: 0
Reputation: 599540
Use elif
for the subsequent comparisons, so that only one is done per iteration.
Upvotes: 1