Hi guys.
I’m making a small zombie game and I need to detect what the player is looking at all the time without raycasting, as I’m aware of the CPU cost of such a function.
I know of OnMouseEnter() and it’s other functions, but I’m not sure if that would be better than a raycast. It is my last fallback as an alternative to raycasting, unless the player pushes a button to raycast so it is not raycasting all the time?
Does anyone have any ideas?
How do the big games do it?
Rust for example, when you look an object such as a campfire, it will open a GUI. This is done in unity and not sure if it’s OnMouseEnter()
CausticLasagne.
Not sure what you mean by “the CPU cost of such a function” - raycasting is a pretty cheap operation - it’s just an intersection test for each object checked until a hit is found - I’d be hugely surprised if a single raycast every frame makes even the slightest difference to your performance.
Still, if you have reason to believe that it’s a performance bottleneck, there are some things you can do to make it more efficient:
- Do you need it to be every frame? You could use a coroutine or InvokeRepeating() to schedule a raycast, say, 10 times a second instead, which might provide perfectly acceptable response.
- Set up your collision matrix correctly so that you’re not performing intersection tests against every object - only against those that you want to register whether the player is looking at.
- Use simple colliders rather than complex mesh colliders to make the intersection algorithm more efficient.
- Limit the length of your raycast - there’s no point extending a ray to infinity if you only want your player to be able to “look” at things within 10m in front of them, say.
@tanoshimi.
You’re a genius.
I could use invoke to do raycasting as I don’t need it every second.
The use of layers is also good, another idea I’d not thought of.
I thought it was cpu intensive to raycast every frame?
Anyways, thanks for the pointers.
CausticLasagne.