Issues with while loop

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

I’m having issues with the while loop
More details
I’am trying to make a game and the player can change their scale.x and scale.y
Having normal animations in this case wouldn’t be possible
So i did it with code but when i press the jump key the game ceashes
The code:

func  start_jump_anim():
     if Input.is_action_just_pressed("jump"):
          while jump_max_scale_x > jump_min_scale_x:
               self.scale.x += jump_anim_scale_x_increasing_speed
               while self.scale.x == jump_max_scale_x + self.scale.x:
func end_jump_anim():
     self.scale.x –= jump_anim_scale_x_changing_speed
     if self.scale.x == self.scale.x – jump_max_scale_x:
          self.scale.x = self.scale.x
:bust_in_silhouette: Reply From: skysphr

Consider using a Tween instead of modifying the properties manually; it is significantly less tedious and you also get some nice features such as non-linear interpolation, which is often times more visually pleasing.

If using a Tween is not an option, you should note that the entirety of the while loop runs inside a single frame; as such, the effects would occur instantaneously, not over a period of time. Consider something like this instead:

enum jump_states { NONE, INCREASING, DECREASING }
var jump_state = jump_states.NONE

func _on_jump_pressed():
    jump_state = INCREASING

func _physics_process(_d):
    if jump_state == jump_states.INCREASING:
        if scale.x < jump_max_scale_x:
            scale.x += jump_anim_scale_x_increasing_speed
            jump_state = DECREASING
    elif jump_state == jump_states.DECREASING:
        if scale.x > jump_min_scale_x:
            scale.x -= jump_anim_scale_x_changing_speed
            jump_state = NONE

(more or less pseudocode, you will have to adapt it to fit your needs)

Note that appending self. in front of local variables is unnecessary unless you are trying to call a setter or getter. Also note that function calls need the () to run.

I totally forgot about the tween node
Anyway thx

trien | 2022-03-27 14:05