I made this guard rotate towards the player when he enters his field of view, but I'm having a problem: he follows the player only until the angle of the player gets to 180 or -180, because when I go over that it turns negative or positive, respectively, and no longer falls within the view range from the left_boundary to the right_boundary (image below).

(EDIT: I tried inverting angles in several ways and stuff like that. Either it doesn't work, or I missed the right way to do it.)

Here's how I'm doing it:

var idle_view_left_boundary 	= 45	# defaults for idle state
var idle_view_right_boundary 	= -45

# (...)

func detect_player():
	# if player within range of sight	
	if distance_to_player < radius_3 
		
		# I calculate the boudaries based on rotation
		left_boundary = get_rot() + deg2rad(idle_view_left_boundary)
		right_boundary = get_rot() + deg2rad(idle_view_right_boundary)
		
		# then the angle (according to "AB = A - B" from the vector math page of the docs)
		var player_angle = Vector2( player.get_pos() - get_pos() ).angle()
		
		# then I check if the angle is within the boudaries
		player_in_sight = player_angle <= left_boundary and player_angle >= right_boundary

		# and if it is... do a murderous stare
		if player_in_sight:
			set_rot(player_angle)

And a visual representation of the result:

Maybe it would help to use a Vector for the direction the enemy looks at and to use the angle_to method to get the angle between the direction vector and the Playerpos-Enemypos vector. something like: direction = Vector2(1,0).rotated(get_rot()) # or Vector2(0,1).rotated(get_rot()) depending on the default direction player_angle = Vector2( player.get_pos() - get_pos() ).angle_to(direction)

@x1212 I tried using the Vector2.angle_to() before and it wasn't giving me the correct angle, but I was doing it differently. It may work the way you're saying. Meanwhile I managed to make it "work" by inverting the guard's angles before they reach 180/-180, so I decided to prioritize some other stuff. I'll tackle the issue again later.

@Avencherus I will try that too. One thing, though: you're suggesting using velocity's direction. What if the player is standing still (velocity (0,0)) while the guard is still turning? I don't think there's much chance of that happening, there's no delay in turning or anything, and I don't plan to have any, so probably it's not an issue. I'm just wondering.

6 years later

use the look_at() function

3 months later