+1 vote

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.

in Engine by (48 points)

1 Answer

+2 votes

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.

by (3,891 points)
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.