- Home /
Check if object is inside a viewing radius
Very likely theres some trigonometry to this, but i cant figure it out.
Heres an example of what im trying to accomplish. The cone is inside the viewing angle, the cube is not. And the sphere is the caster.
So has anyone done this before? and if so, how did you do it?
Thanks to hexagonius, this is resolved. Solution :
public float min = -60f;
public float max = 60f;
bool InsideViewAngle(Vector3 point)
{
Vector3 dirVec = (point - transform.position).normalized;
float up = Vector3.Dot(transform.up, dirVec) * 90f;
float down = Vector3.Dot(-transform.up, dirVec) * 90f;
/*
* if player is below the object
* up will return -90 and down will return 90
*
* if player is on the same vertical level as the object :
* up and down will return 0
*
* if player is on top :
* up will return 90 and down will return -90
*/
//if up is greater than min(-60), and is less than max(60);
return up > minVertical && up < maxVertical;
}
Answer by hexagonius · Dec 19, 2015 at 06:13 AM
The first question is "what is considered inside the radius? center point? first sight?"
I think for the first one you can use the Dot product of vector "sphere forward" and "sphere to object", and the same with sphere backward. the result of 1 means exactly in front. a 0 means it's at a 90° to it. I think a 45° is a 0,7..something, like the sin or cos of that angle.
with the second it's easier, I guess, to programmatically create a polygoncollider2D with the shape of the view. trigger enter and exits will tell you then.
last approach would be to use cameras looking both ways. OnBecameVisible can tell when an objects comes into real view.
yeah, well... that's what you learn when testing about that stuff, right ;)
Or you simply use Vector3.Angle which does the normalizing and converting of the dot product into degrees for you ^^. So you can naturally work with angles. $$anonymous$$ultiplying the result of the dot product with "90" makes no sense. The value isn't linear as it represents the cosine of the angle between the two vectors. You have to use $$anonymous$$athf.Acos to convert it to an actual angle in radians. $$anonymous$$ultiply that result with $$anonymous$$athf.Rad2Deg and you get the angle in degrees.
And by using ILSpy you can see how Vector3.Angle is defined:
public static float Angle(Vector3 from, Vector3 to)
{
return $$anonymous$$athf.Acos($$anonymous$$athf.Clamp(Vector3.Dot(from.normalized, to.normalized), -1f, 1f)) * 57.29578f;
}
The "57.29578f" is basically what is stored in $$anonymous$$athf.Rad2Deg. It's simply (180 / PI)
Your answer
![](https://koobas.hobune.stream/wayback/20220612053155im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
raycast and trigonometry 2 Answers
How to get an offset of a RaycastHit? 0 Answers
Why multiply a vector by -2? 1 Answer
Find third point resulting in a right angle triangle with 2 known points 1 Answer