Selecting animation based of player

Godot Version

4.6.2

Question

I am trying to get a boss to have animations, and I am wondering if I can select the boss’s animation based off the direction it is moving in?

extends Node2D

@export var player: PlayerController
@onready var animation_player = $AnimationPlayer
# Called when the node enters the scene tree for the first time.
func _ready() -> void:
	pass # Replace with function body.


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	var to_player = player.position - position
	var dir = to_player.normalized()

	animation_player.play("upWalk")

use dot() on the normalized direction to figure out which of the 3 axes is most aligned with the character’s movement. You may have to employ some world-space local-space transform3D trickery to get the algorithm to use the right directions.

# figure out what the character's up/down, left/right and front/back directions
# are in world space, compared to its movement
var my_directions = basis.orthonormalized()
var up_down = dir.dot(my_directions.y)
var front_back = dir.dot(my_directions.z)
var left_right = dir.dot(my_directions.x)

#quick and dirty way to find the closest direction to snap to 
var direction_alignment = [up_down, front_back, left_right]
var index_of_max = 0
for i in 3:
  if direction_alignment[i] > direction_closeness[index_of_max]:
    index_of_max = i
    pass
  pass
match index_of_max:
  0:
    # play animation of vertical movement 
  1:
    # play animation of front/back movement
  2:
    # play animation of left/right movement
  pass

Remember: if the characters are node2D or node3D, they will inherit whatever transform their parents have, thus if the player and the boss are not siblings under the same parent the calculations will be wrong and you’ll have to use their global positions and basis matrices instead.

Thank you!