0 votes

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)
in Engine by (21 points)

1 Answer

0 votes
Best answer

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")
by (7,190 points)
selected by

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.