Newbie here. Need help with updating direction in player.gd

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()

First, please format your code with the </> tool. It’s so hard to read it.

I think, just a head-run here, that your moveDirection.x may often be < 0. Therefore it’s constantly setting lastDirection to “Left”

Hello, it’s not necessarily the answer in and of itself, but I’m wondering if these could help you:

  • It could be more straightforward to actually keep the last direction as a vector (lastDirection = moveDirection), and do the if moveDirection.x < 0 check in the updateAnimation method.
  • You’re repeating both animation.play("side_walk") and print(lastDirection) for every condition in your if/else statement in updateAnimation. You can place them right under “else” so that the rest of the code only handles the “sprite flipping”.

Sorry that this is not an actual answer, but these little things can sometimes help narrow down the places to look at :slight_smile: