###4.3 Godot Version
Question
I am following a tutorial and everything works except for my character doesn’t change direction. In the tutorial he switches the sprite by changing the state ( state + “_” + animDirection() ) The corresponding animations are labeled as such, e.g. “idle_walk”, “walk_up”, etc. I’m not sure what I’m doing wrong. Thanks in advance!
Here’s the code:
Blockquote
class_name Player extends CharacterBody2D
var move_speed: float = 100.0
var cardinal_direction: Vector2 = Vector2.DOWN
var direction: Vector2 = Vector2.ZERO
var state: String = “idle”
@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var sprite: Sprite2D = $Sprite2D
Called when the node enters the scene tree for the first time.
func _ready():
pass # Replace with function body.
Called every frame. ‘delta’ is the elapsed time since the previous frame.
func _process(delta: float):
direction.x = Input.get_action_strength("right") - Input.get_action_strength("left")
direction.y = Input.get_action_strength("down") - Input.get_action_strength("up")
velocity = direction * move_speed
if setState() == true || setDirection() == true:
UpdateAnimation()
pass
func _physics_process(delta: float):
move_and_slide()
func setDirection() → bool:
var newDirection: Vector2 = cardinal_direction
if direction == Vector2.ZERO:
return false
if direction.y == 0:
newDirection = Vector2.LEFT if direction.x < 0 else Vector2.RIGHT
elif direction.x == 0:
newDirection = Vector2.UP if direction.y < 0 else Vector2.DOWN
if newDirection == cardinal_direction:
return false
cardinal_direction == newDirection
sprite.scale.x = -1 if cardinal_direction == Vector2.LEFT else 1
return true
func setState() → bool:
var newState: String = "idle" if direction == Vector2.ZERO else "walk"
if newState == state:
return false
state = newState
return true
func UpdateAnimation():
animation_player.play(state + "_" + animDirection())
func animDirection() → String:
if cardinal_direction == Vector2.DOWN:
return “down”
elif cardinal_direction == Vector2.UP:
return "up"
else:
return "side"