How to make animated sprites play in all directions based on iput?

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

The get_input() function includes four if statements which all check for input and should play the same run animation no matter which direction it is. When the scene is run, only the up input plays the run animation. I can at least tell this is because it is processed last ("ui_up" is the fourth one checked), but still don’t know why it wont play for the other three directions. What do I have wrong?

I did try replacing the three if statements for left down and up with elif arguments, which lets animations play in all directions but of course doesn’t allow velocity updates to add and normalize (the elif statements prevent diagonal movement):

extends KinematicBody2D

export (int) var speed = 150

var velocity = Vector2()

func get_input():
	velocity = Vector2()
	if Input.is_action_pressed('ui_right'):
		velocity.x += 1
		$Body.play("Run")
	if Input.is_action_pressed('ui_left'):
		velocity.x -= 1
		$Body.play("Run")
	if Input.is_action_pressed('ui_down'):
		velocity.y += 1
		$Body.play("Run")
	if Input.is_action_pressed('ui_up'):
		velocity.y -= 1
		$Body.play("Run")
	else:
		$Body.play("Idle")
	velocity = velocity.normalized() * speed
	
func flip():
	$Body.set_flip_h(get_global_mouse_position().x < global_position.x)
	$Gun.set_flip_v(get_global_mouse_position().x < global_position.x)

func _physics_process(delta):
	get_input()
	flip()
	velocity = move_and_slide(velocity)
:bust_in_silhouette: Reply From: exuin

The problem is the last part of your get_input() function.
This part:

if Input.is_action_pressed('ui_up'):
    velocity.y -= 1
    $Body.play("Run")
else:
    $Body.play("Idle")

What this does is play the “Idle” animation if you’re not pressing the up button. Since it comes last, it overrides all of the other key presses that cause the “Run” animation to play.
I would replace the code with this:

if Input.is_action_pressed('ui_up'):
    velocity.y -= 1
    $Body.play("Run")
if velocity == Vector2(0, 0):
    $Body.play("Idle")

Thank you for the help, that works great! I figured it had something to do with those last two arguments in the function.

Wolff | 2020-09-15 04:09