You made an infinite while loop. The reason it’s infinite is that you never actually update the value of current_speed
. If you do:
#Movemet Modes
if Input.is_action_pressed("Sprint"):
while current_speed < sprinting_speed:
current_speed = current_speed + 0.1
else:
while current_speed > walikng_speed:
current_speed = current_speed - 0.1
Then it will actually update the value, and thus the while loop will eventually end, and your game won’t crash. However, it won’t do what you want (changing speed smoothly), because this whole while loop will be run in a single frame!
Basically, all the code you write in the _process
and _physics_process
will be run repeatedly, every frame. For this reason, it’s pretty rare that you want to use a while-loop in either of these functions (but it does happen).
In order to update the speed smoothly, you’ll want to just update it once per frame:
#Movemet Modes
if Input.is_action_pressed("Sprint"):
if current_speed < sprinting_speed:
current_speed = current_speed + 0.1
else:
if current_speed > walikng_speed:
current_speed = current_speed - 0.1
This still isn’t a very good way to do it, though, for several reasons:
- How fast the speed changes will depend on the framerate
- It’s possible to overshoot the target speed, so you can end up, for example, at a speed slightly faster than the sprint speed, or slightly slower than walking speed
To fix the first problem, choose a higher value than 0.1
, but then multiply it by delta
. To fix the second problem, use the move_toward
function, which will never go past its target value. That way, you can also drop the if-statements checking if the speed is too low or high.
#Movemet Modes
if Input.is_action_pressed("Sprint"):
current_speed = move_toward(current_speed, sprinting_speed, 5 * delta)
else:
current_speed = move_toward(current_speed, walking_speed, 5 * delta)