Problem with making a sprinting function in python Ursina

186 Views Asked by At

I'm making a Mineclone, but am stuck in the sprinting bit.

I want code that will put the player in 'sprinting' mode when you press Ctrl, as long as you have w pressed, and exit sprinting when w is released. Releasing Ctrl while sprinting should do nothing. I tried this code among many others, but when I test it, it freezes.

def update():
    global block_pick

    if held_keys['control'] and held_keys['w']:
        while held_keys['w']:
            player.speed = 10

So the code would check every frame.

1

There are 1 best solutions below

2
On BEST ANSWER

I'm not very familiar with gaming with Python, but if this is vanilla Python and not using some additional library that has to be written differently;

First your code needs to be indented under the update function. Second the code is updating every frame, that means that the whole execution is being re-run every frame rate. So the while loop will prevent frame from updating again.

I can suggest you introduce a global boolean for sprinting, which changes based on which buttons are pressed.

sprint = False # global boolean

def update():
    global block_pick
    global sprint

    if held_keys['control'] and held_keys['w']:
        sprint = True
        player.speed = 10

    if sprint and not held_keys['w']: # check for button pressed while sprinting.
        sprint = False
        player.speed = 1