I have an app, let's say it's a 'Virtual Museum' type of thing. Lots of stuff to look around at.
I need to be able to tell what object(s) are being looked at, checking about twice a second.
Would it be best if
a) A script on the camera used Physics.Raycast logs which object(s) are 'hit'
b) A script on each 'object of interest' logs that the camera is looking at it (Collider.Raycast, right)?
c) Something else?
What I ended up doing was making a prefab which contains a box collider and script. On Update, check if ray cast from camera sees it, hits it. I figured this way, I'd be testing against a simple shape, it wouldn't affect my model prefab (sometimes need to reimport or swap them out), and I just put these around objects I care about. Seems to work pretty well.
answered Jan 28 '11 at 04:29 PM
You would probably want to use something thicker than a Raycast such as a capsule cast, if you are going to use some sort of a cast.
Another easy way would just be to use renderer.isVisible.
Or, you could use the Dot product of the camera's forward Vector and the difference between the object's position and the camera's position. This would probably overly complicated, but Vector math is inexpensive for the most part, and if you can't use a the renderer method, then this might be a good idea. Personally, this is probably more complicated than you want to make it, but it's just another (albeit a bit strange) option.
answered Jan 19 '11 at 01:40 AM
Check if a screen rect contains the object's position using WorldToScreenPoint:
Since you only need it twice per second, you'd use InvokeRepeating instead of Update. You'd also want to make sure the objects are in front of the camera; the most optimal thing would probably be to make a List of transforms, and have the objects add/remove themselves to and from the list using OnBecameVisible and OnBecameInvisible, then cycle through that array (instead of having each object run that script). You can use Vector3.Distance to see if an object that's being looked at is close enough.
answered Jan 19 '11 at 02:00 AM