Godot Version
Latest
Question
How do I make this code so that my player’s sprite will go to idle at the same direction the player stopped walking in? I cant make the "var direction = “3"” as “none” make it not reset back to sprite “3”
extends CharacterBody2D
@export var speed: int = 150
@onready var animations = $AnimatedSprite2D
var moveDirection = “none”;
#Handles User Input
func handleInput():
moveDirection = Input.get_vector(“A”,“D”,“W”,“S”)
#Velocity is a speed into a given direction
velocity = moveDirection * speed
func updateAnimation():
var direction = “3”
if velocity.x > 0: direction = “0”;
if velocity.y < 0: direction = “1”;
if velocity.x < 0: direction = “2”;
if velocity.y > 0: direction = “3”;
if velocity.length() == 0:
animations.play(“spr_player_idle” + direction)
else:
animations.play(“spr_player_walk” + direction)
#Activates Physics
func _physics_process(delta):
handleInput();
move_and_slide()
updateAnimation()
Hi, you can store the last “non null direction input” inside a variable (that you simply set in handleInput()
to the same value as moveDirection
only when its length is > 0.
Then, inside updateAnimation()
, just use this new variable to compute the animation index.
Didn’t test, but I guess that would work fine. Let me know if it does not!
1 Like
Thanks, but I fixed it. I ended up redoing some things.
extends CharacterBody2D
#Nodes
@export var speed: int = 150
@onready var animations = $AnimatedSprite2D
@onready var sfx_walk = $sfx_walk
#Variables on creation
var moveDirection = “none”;
var direction = “3”;
var state;
var sfx_walk_playing = false
#Handles User Input
func handleInput():
moveDirection = Input.get_vector(“A”,“D”,“W”,“S”)
#Velocity is a speed into a given direction
velocity = moveDirection * speed
func updateAnimation():
if moveDirection == Vector2.ZERO:
return
if moveDirection.x > 0:
direction = “0” # “D” or right
elif moveDirection.x < 0:
direction = “2” # “A” or left
if moveDirection.y > 0:
direction = “3” # “S” or down
elif moveDirection.y < 0:
direction = “1” # “W” or up
func selectAnimation():
if velocity == Vector2.ZERO:
state = “idle”;
else:
state = “walk”;
animations.play(“spr_player_” + state + direction);
#Player State Function
func playerState():
match state:
“idle”:
#Do not play walk sound
if sfx_walk_playing:
sfx_walk.stop()
sfx_walk_playing = false
"walk":
#Play walk sound
if not sfx_walk_playing:
sfx_walk.play()
sfx_walk_playing = true
#Activates Physics
func _physics_process(_delta):
handleInput();
move_and_slide()
updateAnimation()
selectAnimation()
playerState()
1 Like