- Home /
What's the most efficient raycast distance, and why?
Assuming i'm casting against something specific (to see if the path to it is obstructed);
Is it most efficient to set the cast distance to exactly what i need, and no more Or is it best to use some constant value like infinity?
Also, does raycast performance depend solely on the colliders in its path? Does a raycast extending off infinitely into the distance cause any more overhead?
Raycasting for a longer distance is of course more CPU expensive since (I$$anonymous$$O) the engine rounds up all the colliders in that radius (so infinite means all colliders) and raycasts against them. So it is better to use the distance that you need ex. 20 meters rather than infinity.
are you sure about that? in that case it sounds like casting for infinity is devastatingly expensive.
i'l see what kind of results i get from calculating a distance
Answer by EvilTak · Dec 09, 2014 at 02:05 PM
Raycasting also involves broad phasing, ideally first all objects outside the radius of the distance value are filtered out (thus infinite distance means no colliders are filtered out) . Then the bounds check comes into play. Collider.bounds is used (see Bounds.IntersectRay). Then as @NoseKills said, the actual raycast is done. The remaining colliders are raycasted (closest one first) and if it is a concave collider it can be pretty expensive depending on the complexity of the collider. Primitive colliders usually have better raycast performance than mesh colliders.
Answer by NoseKills · Dec 09, 2014 at 01:56 PM
Like @Evil Tak says, physics engines usually optimise things by filtering out objects first by some really cheap calculation. For example by checking whether the bounding volume or AABB (in 2D) of the object is in range of the ray.
Only after that they check the remaining objects' geometry to see if the ray actually passes through a hole in the object mesh's geometry or does it really hit it, since this can be a very heavy calculation depending on the object's complexity.
Of course Unity is not Open Source so we can't know for sure... but I'd be very surprised if the ray length didn't matter.
I don't know why everyone misses the space in my username...
I saw it but still couldn't find a way to write an " @ " reference to it. Do you know how to do it ?
EDIT: @Evil Tak O$$anonymous$$ so it's just the preview that is FUBAR and misleads people
Sorry I was typing my answer... The name is finally right, thank god! People always do it without a space and it redirects to some @EvilTaco who isn't even active on this site...
So far in my testing, adding a limited range by grabbing the magnitude of my direction vector slows things down massively. Using the sqr$$anonymous$$agnitude seems to have no effect on performance, probably due it being such a large number that everything is within the radius anyway
How many objects do you have in your scene? Aand what platform are you targeting?