I’m creating a test scenario for an HMD-controlled strategy game. One of my Use cases covers the group selection, which essentially tries to select all visible units of the same type group (e.g. “soldier”, “grenadier”, “horseman”). I am currently working with Raycasts to select single objects.

Is there a way to “raycast” the whole viewport and check for all hit objects of a specified layer?

Is there an even more efficient way to identify objects currently visible in the viewport?

Honestly doing that much raycasting would be very intensive. You’d be better off looping through all objects in the scene that are nearby, and checking their difference in angle. You can get the angle between vectors and check if it’s less than the field of view.

Create one vector that is pointing directly forward from the eyes, then the other vectors are created by taking the object position and subtracting the location of the eyes. To get the angle between the vectors get the dot product of the two vectors, divide the dot product by the product of both vector’s magnitudes and then pass that value in to the arc cosine (acos). Note that the resulting angle will be in radians not degrees, to convert to degrees multiple the radians by 180/pi (approx. 57.2957795)

If you want to forgo that math yourself, you may use both the Vector2 and Vector3 Angle function, this function returns the angle (not radians) and is always positive, which for your case if fine.

```
Vector3.Angle(vectorToObject, vectorPointingForward) < FoV;
```

If your scene has a lot of objects in it you must be careful, as in VR it’s very important you get high framerates, and with the refresh rate, the resolution and the fact that the scene is rendered twice for each eye essentially you can’t afford too many extremely costly operations.