trying to figure out animation and if statement

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

Hello,

hopefully someone can assist, i have a GDScript, which it was C#, however C# is not doing so well, already found bugs on my first week of trying godot… anyways, what i am trying to accomplish is if character is moved right, then animation start or rotate etc., if left, same, but if stopped, play idle and stand in position.

Left works fine, however right doesn’t… what am i doing wrong??

GDscript is below:

extends KinematicBody2D


var sprite_node 

export (int) var run_speed = 300
export (int) var jump_speed = -600
export (int) var gravity = 1200

var velocity = Vector2()
var jumping = false


func _ready():
    set_process(true)
    set_process_input(true)
    sprite_node = get_node("Main_Character")

func get_input():
    velocity.x = 0
    var right = Input.is_action_pressed('ui_right')
    var left = Input.is_action_pressed('ui_left')
    var jump = Input.is_action_just_pressed('ui_select')

if jump and is_on_floor():    
    jumping = true
    velocity.y = jump_speed
if right:
    velocity.x += run_speed
    sprite_node.set_flip_h(false)
    $Main_Character.play("Run")
if left:
    velocity.x -= run_speed
    sprite_node.set_flip_h(true)
    $Main_Character.play("Run")
else:
    $Main_Character.play("Idle")

func _physics_process(delta):
    get_input()
    velocity.y += gravity * delta
    if jumping and is_on_floor():
        jumping = false
    velocity = move_and_slide

thanks in advance

:bust_in_silhouette: Reply From: p7f

What you are doing wrong is that the else case affects only to if left. So when you have right and no left it will enter the else and set animation to idle. Try something like this:

if jump and is_on_floor():    
    jumping = true
    velocity.y = jump_speed
if right:
    velocity.x += run_speed
    sprite_node.set_flip_h(false)
    $Main_Character.play("Run")
elif left:
    velocity.x -= run_speed
    sprite_node.set_flip_h(true)
    $Main_Character.play("Run")
else:
    $Main_Character.play("Idle")

This however would make pressing both left and right at the same time not cancelling each other. You can try then something like this:

if jump and is_on_floor():    
    jumping = true
    velocity.y = jump_speed
if right:
    velocity.x += run_speed
    sprite_node.set_flip_h(false)
    $Main_Character.play("Run")
if left:
    velocity.x -= run_speed
    sprite_node.set_flip_h(true)
    $Main_Character.play("Run")
if velocity.x == 0:
    $Main_Character.play("Idle")

I would also set flip to true only when velocity.x < 0, and to false when velocity.x > 0 so it does not get flipped when pressed both right and left which should make no movement. Also you can add and not jumping to the last if so it does not start iddle when jumping.