How to turn one node towards another in 2D

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Deith

I know this is a very simple question but I’m new to vectors and calculating them so I just get confused.

I have an NPC scene with AnimationSprite that has four animations: up, down, left, right and I have a player that I want to basically turn the NPC towards (by playing correct animation). I have both NPC position and player position and I just can’t figure out how to calculate whether the player is on the right, left, above or below and I don’t want to just make dozen if statements. So how do I calculate that? I know the answer is right there and it’s very simple I just can’t visualise it.

:bust_in_silhouette: Reply From: Wakatta

Try the following and you can replace global_transform.origin with position the former is used to show interchangeability with 3D

var animations = {
	Vector2.UP : "up",
	Vector2.DOWN : "down",
	Vector2.LEFT : "left",
	Vector2.RIGHT : "right"
}

func face_player():
	var origin = $Player.global_transform.origin - global_transform.origin
	var animation = "idle" # default animation
	var distance = 100 # default distance

	for face in animations:
		if origin.distance_to(face) < distance:
			#update distance to the lowest value
			distance = origin.distance_to(face)

			# choose animation
			animation = animations[face]

	$AnimatedSprite.play(animation)

For some reason just know there’s an easier way, can practically feel it in my bones yet this is all that comes to mind right now.

:bust_in_silhouette: Reply From: Deith

I solved it by making Idle animation for the NPC with animationPlayer instead, and just input (player_position - npc_position).normalized() as vector for animationTree.