Unity 3D: Calculating something is within viewing range (C#)

Posted on Updated on

If you ever want to calculate the viewing angle of a character you “could” use Quaternion.Euler to calculate the x, y & z coordinates .. which would probably look something like:

float viewAngle = 90.0f;
// ...
Vector3 direction = Quaternion.Euler(0.0f, 90.0f, 0.0f) * (gameObject.transform.localPosition - this.transform.localPosition).normalized;
float dot = Vector3.Dot(CurrentDirection, direction);
if(dot < viewAngle)  
	// not in viewing angle .. so exit loop and do something else

But i think this looks more complicated than it should be. So instead, use Vector3.Angle to get the forward position of your character already, subtract it from an enemy character/obstacle/whatever then check whether it is less than or equal to the viewing angle. You’ll know when something is in front of your character and within viewing ange or

//  Can now see
float viewAngle = 90.0f;
// ...
if(Vector3.Angle(transform.position - gameObject.transform.position, transform.forward) <= viewAngle)
	// do something

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s