Godot Version
4.2
Question
After struggling to debug for two hours, I eventually gave up. Below is the code from my player.gd file. My intention is to trigger the side_walk animation when moving up or down, depending on the lastDirection variable, which stores either “left” or “right”. However, I encountered an issue where pressing the up or down keys always results in the lastDirection variable printing “left”, even if I had just pressed the right button before moving up or down. Consequently, the side_walk animation consistently flips. How can I resolve this problem?
extends CharacterBody2D
@export var speed: int = 200
@onready var animation = $AnimatedSprite2D
var lastDirection = ""
func handleInput():
var moveDirection = Input.get_vector("ui_left","ui_right", "ui_up", "ui_down")
velocity = moveDirection * speed
if moveDirection.x != 0: # If moving horizontally
if moveDirection.x < 0:
lastDirection = "Left"
else:
lastDirection = "Right"
func updateAnimation():
if velocity.length() == 0:
animation.play("side_idle")
else:
if lastDirection == "Left":
animation.flip_h = true
animation.play("side_walk")
print(lastDirection)
elif lastDirection == "Right":
animation.flip_h = false
animation.play("side_walk")
print(lastDirection)
if velocity.x != 0 or velocity.y != 0:
print(lastDirection)
animation.play("side_walk")
func _physics_process(delta):
handleInput()
move_and_slide()
updateAnimation()