- Home /
detecting an object distance behind an other one with a raycast
hi, i was wondering if there is a way to detect the distance between an object i am looking at and the other object behind it with a raycast? for example i whant to look a a crate and when i press lets say "E" it check if the object is let say 5 unit or closer to the crate and if it is, it then do someting and all that using raycast. you must keep in mind that they will be more then one crate.
Do you need to raycast the first object? If not use a layer on it so that it gets ignored.
I need the raycast to hit the first object and then detect the distance between that point it hit and the object behind it
What you can do is this.
1: Raycast to the first object and store it's distance
2: Add the second object to a Layer
3: Raycast again with layer$$anonymous$$ask, so
you can ignore everything except the Layer, that the second object is and store it's distance.4: subtract the distance of the first object, from the second's distance...
You can use Physics.RaycastAll() to get multiple hits. The hits will not necessarily be sorted by distance.
Answer by kumarc123 · Sep 18, 2013 at 07:12 AM
You can easily do it
Use Physics.Raycast (other.position, Vector3.back, hit).
Check if hit.gameObject ot transform is the desired one or not. Ex: if (hit.gameObject.tag == "target")
get the distance from hit.distance property
Thats it