extends CharacterBody2D
func _input(event):
while event.is_action_pressed(“move_left”):
position.x -= 2
if event.is_action_released(“move_left”):
break
when I tried to run this code, there is an overflow error, so i was wondering if I am using the while loop correctly and how could my code get fixed
That is not the right way to do it. The right way is
If Input.is_action_pressed(“move_left”):
##Do something
I am assuming that your indentations are right. In that case you don’t need while loop instead use:
if event.is_action_pressed("move_left"):
position.x -= 2
1 Like
while loops do not wait for any time to pass, they take hog the game’s thread until they are false, they are only run for a single frame and will make that frame as long as the condition is true. Your condition is “if this event is pressed” which remains true forever, that event will always remain pressed because the while loop does not let anything else happen when it’s running, Godot cannot process more inputs until the while loop is complete.
Try studying the basic platformer movement template that comes with Godot 4.x when attaching a script to CharacterBody2Ds. It modifies velocity
within the _physics_process
function to move the character by checking which buttons are held every frame, once per frame.
1 Like