Angle between two objects relative to an objects current angle

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

I’m trying to tell if the player is within a 120 degree viewcone in front of an enemy. I’m having an issue figuring out the angle between the two relative to the enemy’s rotation.

So I get the angle between the player and the enemy:

var angle = rad2deg(Vector2(pos.x, pos.z).angle_to(Vector2(ppos.x - pos.x, ppos.z - pos.z)));

And then I get the rotation of the enemy:

var myrot = rad2deg(transform.basis.get_euler().y);

So how do I get the angle relative to the enemy’s rotation? I had assumed it’d just be adding them together, but that makes it difficult to make sure that the angle is within the 120 degree viewcone, as the added angles will often be higher than the angle should even be able to go.

:bust_in_silhouette: Reply From: SIsilicon

Angles can be pretty messy to work with. We can instead work with vectors. Assuming your enemy faces its local z-axis:

#this function is inside the enemy's script
#returns a bool (whether player_pos inside view cone)
#fov is in radians and player pos is in world space

func inside_fov(player_pos, fov):
    var facing = transform.basis.z
    var player_to_enemy = player_pos - global_transform.origin
    var cos_theta = dot(player_to_enemy, facing)
    return acos(cos_theta)*2.0 < fov

If it doesn’t face it’s local z-axis but a different direction, change the axis used in the facing variable.

P.S.- I made this function on the spot. I haven’t tested it yet, but it should theoretically work.