NPC Won't Turn to The Player Properly

Godot Version

Godot 4.7

Question

So I’m trying to make my NPC turn to the player, but I just couldn’t find a way to make it work. This is the last code I tried using.

func _physics_process(delta: float) -> void:
	if player.position.x > position.x:
		$AnimatedSprite2D.play("Idle_Up")
	if player.position.x < position.x:
		$AnimatedSprite2D.play("Idle_Down")
	if player.position.y < position.y:
		$AnimatedSprite2D.play("Idle_Right")
	if player.position.y > position.y:
		$AnimatedSprite2D.play("Idle_Left")

They only turn to the left and right, which I believe is because the left and right code appears before, but it’s not just that either, but I also have to be on the exact x value as the NPC for them to look left or right of the player anyways. This happened the other way around as well by the way, and what I wanted was for there to be sections that the player had to be in for the NPC to look at the player. Kind of like a quarter circle.

I would really like some help here.

I can see two problems, for one you flipped the directions. In godot, +X is right and -X is left, as well as +Y is down, and -Y is up. Also your if statements can be true further down. Your first animation might play correctly, but then another if statement will just override it.
I’m really not that good with GDScript, but something like this should work:

func _physics_process(delta: float) -> void:
	var direction: Vector2 = player.position - position
	if abs(direction.x) > abs(direction.y):
		if direction.x > 0:
			$AnimatedSprite2D.play("Idle_Right")
		else:
			$AnimatedSprite2D.play("Idle_Left")
	else:
		if direction.y > 0:
			$AnimatedSprite2D.play("Idle_Down")
		else:
			$AnimatedSprite2D.play("Idle_Up")

Thanks! this worked well. I might do some research on absolute values, because to be honest, I have no idea how they work, but if it can be used for stuff like this, then it might be good to learn it.