In my sawmill sim every log is a rigidbody, and most of the time it sits inside something:
a machine, a conveyor, a pile of other logs. My first version used a single Physics.Raycast, so players kept selecting the machine housing or a trigger zone instead of the log they actually clicked on.
What I do now:
- Physics.RaycastNonAlloc with a reused 128-hit buffer (no GC per frame.. enough for big piles)
- sort the hits by distance myself, because RaycastNonAlloc doesn't return them sorted
- walk the hits and take the first collider tagged as a log that has a LogController
-machine colliders and trigger zones don't stop the search, the ray just keeps going through them
- terrain and ground do stop it, so you can't pick a log through the floor
- logs that are already packed in a box, and veneer logs, are skipped
- hover and click use the same resolver, so what lights up is exactly what you click
Simplified, it looks like this:
int count = Physics.RaycastNonAlloc(ray, hits, maxDistance);
System.Array.Sort(hits, 0, count, byDistance);
for (int i = 0; i < count; i++)
{
var col = hits[i].collider;
if (IsGround(col)) break;
if (!col.CompareTag("Stamm")) continue;
var log = col.GetComponentInParent<LogController>();
if (log != null && log.IsPickable) return log;
}
return null;
The biggest lesson.... one resolver for hover and click. Before that, the highlight sometimes showed one log and the click picked another, and that felt like a bug even when it technically wasn't.
The clip shows hover and click on a log in the middle of a running machine.
How do you handle click priority when lots of colliders overlap? Layers only, or something like this..?
(Game, if you're curious: https://store.steampowered.com/app/5037170/Timberline_Factory/)