Unable to make this code run 3 times

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By GamelandX

Hi all, Im trying to throw a ball, sort of like angry bird, but I want to be able to launch the ball 3 times once it has stopped usually takes about 5 secs or less in theory, I tried adding a while loop but my game freezes when I run it, everything else works as intended.

 extends RigidBody2D
    var dragging
    var drag_start = Vector2()
    var launched = false
    var tries = 3
    func _input(event):
    	while tries != 0:
    		if event.is_action_pressed("click") and not dragging and not launched:
    			dragging = true
    			drag_start = get_global_mouse_position()
    		if event.is_action_released("click") and dragging:
    			dragging = false
    			launched = true
                        tries -= 1
    			var drag_end = get_global_mouse_position()
    			var dir = drag_start - drag_end
    			apply_impulse(Vector2(), dir * 5)
    			yield(get_tree().create_timer(5.0), "timeout")
    			launched = false

Could you share the project so i can see in detail? Shouldnt you use if instead of while? Because you need the code to be executed once per input, dont you?

p7f | 2019-01-13 14:07

:bust_in_silhouette: Reply From: TecoSV

Try to add this line at the end of the while loop:

yield(get_tree(), "idle_frame")

This line prevents that the game freezes in the loop so
this should fix your problem :slight_smile:

:bust_in_silhouette: Reply From: eons

while tries != 0 will be always true for the events you are not looking for, and _input fires on every event, that results on an infinite loop for almost any action.

Change that while tries =! 0 for an if tries != 0

_input gets an atomic event, and should be used to process a single event, do not use loops inside or complex processing or you will freeze the game during input handling, use it to set variables and process your game logic in _process or _physics_process instead.

Also make use of breakpoints to see what is happening when conditions do not work as expected.