Find an object within certain angle in front of current object.

Hey,

Drawing:

              .'
            .'
          .'
        .'   [] //GameObject I want returned.
[   ]--'       //Angle of objects that I want returned.
        '.
          '.
            '.
              '.

So, the first bracket is game object, it scans in front of it at some angle, and returns any gameobjects within that angle, (I’d like the nearest, but I can figure that out). I’ve been trying to think of how I can get this to work, and I know of methods such as SweepTest, which does roughly what I want, or a simple raycast, but I want it within an angle, not the “sphere” that does 360. I’ve thought of combining a raycast with a rotating object that’d rotate a certain degree amount and return an array of objects hit (If any) but I don’t know how angles work to well, as in, I don’t know how to have it literally rotate and while it rotates, it searches and returns (If you can help me with examples, I don’t know Eular/Quartarians to well, and I’ve read the documentation, but their aren’t any manually rotate an object that I could find). Finally, my last case I could do, but I don’t want to, is spawn the item with 2 empty game objects at the angles I’d like to check, then it simply starts rotated to one, then rotates the other real fast and checks, but this seems a shoddy way of doing it…

My current code that doesn’t work (Maybe spark imagination in you? =P):

    var listOfObjects = Physics.OverlapSphere(this.gameObject.transform.position, 50);
	for(var i = 0; i < listOfObjects.length; i++)
	{
		var angle = Vector3.Angle(listOfObjects*.gameObject.transform.position, gameObject.transform.position);*
  •  if(angle > 1 && angle < 25)*
    
  •  {	*
    

_ return listOfObjects*.gameObject;_
_
}_
_
}_
_
return null;*_
It’s a 2D thing though, so i don’t need anything from other angles.
Any help/links would be appreciated.

In your code, Vector3.Angle takes two directions. In other words (7,0,0) represents East, not a spot on the map. The example in the script reference for Vector3.Angle is what you need (find the angle between “target minus me” and “my forwards”.)

The angle is always positive (it won’t tell you if 10 degrees is clock or counter-clockwise) so can just check if(angle<25)

A problem with the angle method is you miss things very close to you. Imagine a large cow one unit ahead at 45 degrees. A 25-degree angle test misses it, even though its rear legs are right in your face. Widening the angle for close objects seems to help.

For a collider method, maybe you could make a big wedge-shaped mesh and use that as a meshCollider for a triggerBox (not sure meshColliders are allowed for that.)