Search code examples
pythonpygamepgzero

Character Animation happens very fast


Please find below code using the PyGame Zero Library

The character animation in the function trex_move() happens very quick despite applying clock.schedule.

The animation, therefore, does not look natural. Is there any way to slow down the animation?

import random

TITLE = "T-Rex Run"

WIDTH=500
HEIGHT=500

GAP = 200

trex = Actor('run1',(100,235))
cactus = Actor('cactus1',(200,235))
trex_run = ['run1','run2']

all_cactus = ['cactus1','cactus2','cactus3','cactus4','cactus5']

JUMP = 0.15
JUMP_VELOCITY = -7
SPEED = 5

x=0
trex.vy = 0

def draw():
    screen.fill((255,255,255))
    screen.blit('floor-1',(0,250))
    trex.draw()
    cactus.draw()
def reset_cactus():
    cactus.image = random.choice(all_cactus)
    cactus.pos = (WIDTH, 235)
def update_cactus():
    cactus.left -= SPEED
    if cactus.right < 0:
        reset_cactus()

def move_cactus():
    speed = 5
    cactus.left-=SPEED
    if cactus.left>WIDTH:
        cactus.right=0

def test():
    #pass
    trex.image = trex_run[x]
    print("test1")

def trex_move():
    global x
    if trex.y == 235:
        trex.image = trex_run[x]

        x += 1
        if x > 1:
            x = 0
        clock.schedule(test,1.0)
    else:
        trex.image = 'jump'

def update():
    update_cactus()
    trex_move()
    if keyboard.up or keyboard.SPACE:
        trex.vy = JUMP_VELOCITY


    trex.vy += JUMP*2
    trex.y += trex.vy
    if(trex.y > 235):
        trex.y = 235

The Actor has two frames, both the frames are now running super fast despite defining a clock with a 1 second delay.


Solution

  • You have to show the same image for multiple frames. Define how many frames the same image should be shown (e.g. frames_per_image) and switch the image after the frames have been exceeded. Use the // (floor division) operator (see Binary arithmetic operations) to compute the index of the current image (x // frames_per_image). e.g:

    def trex_move():
        global x
        if trex.y == 235:
    
            frames_per_image = 10
            trex.image = trex_run[x // frames_per_image]
            x += 1
            if x // frames_per_image >= len(trex_run):
                x = 0
        else:
            trex.image = 'car64'