- Home /
Is there a limit on the distance of raycast?
I'm using this line of code:
if (!Physics.Raycast (Camera.main.ScreenPointToRay(Input.mousePosition), hit))
return;
And the purpose is to detect if the mouse cursor touched a mesh collider.
And it works just fine on the vast majority of objects. But when I tried it on a REALLY large sphere (the size of a small planet), the above line of code no longer works.
Is there a limit on the distance of either physics.raycast or Camera.main.ScreenPointToRay? And if so, is there a way to increase the distance?
Answer by Bunny83 · Nov 12, 2014 at 11:55 PM
No there isn't. If you don't provide a distance it will default to float.PositiveInfinity. So the ray will literally have a length of "infinity". Raycasting doesn't work by really shooting a ray which will "travel" though the space. The physics system direclty tests the intersection of the ray with any bounding box and finally with the actual colliders of the objects.
Keep in mind that if your ray starts inside a collider and goes "out" of the collider you won't hit the collider. You can only hit a collider on the outside.
Thanks, after testing it more, I think it has nothing to do with the distance from the object to me. It has to do with the size of the sphere itself. If I put a "sphere collider" on the sphere, the code works. But if I use mesh collider, the line above fails, if the mesh is so big. What's weird is, I know the mesh collider is there, because I can walk around on the sphere. But why does the raycast fail to trigger against the mesh collider, simply because the sphere is big...?
Answer by toddisarockstar · Nov 16, 2014 at 04:24 AM
if (!Physics.Raycast (Camera.main.ScreenPointToRay(Input.mousePosition), hit, 100)) return;
your ray is limited to distance of 100 here in world space
Your answer
Follow this Question
Related Questions
Raycast not working on build 0 Answers
Is Raycast relatived to screen resolution? 1 Answer
Raycast stop at distance 3 Answers
Calculate where an object is going to land 0 Answers
How to get distances of GameObjects through SphereCast? 1 Answer