65 lines
1.8 KiB
GDScript
65 lines
1.8 KiB
GDScript
extends Node
|
|
|
|
# sprite_animation_changer.gd
|
|
|
|
# When the player actually changes state or direction, this component will decide
|
|
# which sprite animation should play
|
|
|
|
@export var sprite: AnimatedSprite2D
|
|
|
|
var _cached_dv: Vector2
|
|
var _cached_state: PlayerStateMachine.States
|
|
|
|
var _walking_animation_data = {
|
|
Vector2.LEFT: ["walking-side", true],
|
|
Vector2.RIGHT: ["walking-side", false],
|
|
Vector2.UP: ["walking-up", false],
|
|
Vector2.DOWN: ["walking-down", false]
|
|
}
|
|
|
|
var _idle_animation_data = {
|
|
Vector2.LEFT: ["idle-side", true],
|
|
Vector2.RIGHT: ["idle-side", false],
|
|
Vector2.UP: ["idle-up", false],
|
|
Vector2.DOWN: ["idle-down", false]
|
|
}
|
|
|
|
func OnStateChanged(to_state: PlayerStateMachine.States, _from_state: PlayerStateMachine.States) -> void:
|
|
_cached_state = to_state
|
|
if to_state == PlayerStateMachine.States.WALKING:
|
|
_to_walking_state()
|
|
return
|
|
if to_state == PlayerStateMachine.States.IDLE:
|
|
_to_idle_state()
|
|
return
|
|
|
|
|
|
func OnMovementQueued(dv: Vector2) -> void:
|
|
_cached_dv = Vector2Utils.GetClosestDirectionVector(dv)
|
|
|
|
if _cached_state == PlayerStateMachine.States.WALKING:
|
|
# Direction changed while walking, update animation, just run _to_walking_state again
|
|
_to_walking_state()
|
|
|
|
|
|
func _to_walking_state() -> void:
|
|
if _walking_animation_data.has(_cached_dv):
|
|
var animation_data = _walking_animation_data[_cached_dv]
|
|
var animation_name = animation_data[0] as String
|
|
var is_flipped = animation_data[1] as bool
|
|
|
|
sprite.animation = animation_name
|
|
sprite.flip_h = is_flipped
|
|
sprite.play()
|
|
|
|
|
|
func _to_idle_state() -> void:
|
|
if _idle_animation_data.has(_cached_dv):
|
|
var animation_data = _idle_animation_data[_cached_dv]
|
|
var animation_name = animation_data[0] as String
|
|
var is_flipped = animation_data[1] as bool
|
|
|
|
sprite.animation = animation_name
|
|
sprite.flip_h = is_flipped
|
|
sprite.play()
|