Raycast to multiple objects
Hello everyone, I'm here because I've been stuck on a problem for the whole day. My problem is simple (I guess) but I cannot figure it out: I'm in a 3d enviroment and I have an amount of objects (simple cubes with a Box Collider attached on them), I need to check if the cursor is pointing to one of those cubes and, if so, which of them. I need to retrieve the GameObject of the collider which has been hit by the Raycast so I can perform various operations on it.
In the first place I tried using an array of cubes and using the collider's Raycast method to check which cube was hit, like the following code:
foreach(GameObject cube in carCubes) {
RaycastHit cubeHit;
BoxCollider box = cube.GetComponent<BoxCollider>();
if (box.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition),out cubeHit,100f)) {
//cube was hit
}
}
But then I figured out this wasn't the solution since this algorithm does not consider the order of appearance of those cubes and so if, from the camera's point of view, there was multiple cubes overlapped, it could find as the first hit a cube on the back.
So I moved to the following code:
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition),out hit, 100f) {
//hit
}
But now I cannot figure out which cube was hit by the raycast and that information is crucial because I need to know which face of the cube has been hit with the cursor. So the problem is: how can I get which face of the cube and which cube has been hit ?
I know the problem may be very easy to solve, but I'm still a beginner and I couldn't find out a working solution.
Thank
Answer by toddisarockstar · Mar 31, 2016 at 11:52 PM
using Physics.RaycastAll instead might help you out http://docs.unity3d.com/ScriptReference/Physics.RaycastAll.html
it returns an Array of everything hit so you can loop through for whatever you want.
Thank you for your answer, but I still have a doubt: if the array it returns contains all the the object the raycast has hit, how can I know which RaycastHit was the first one to be hit from the camera's point of view ? For example excluding all the objects behind the first one in order of appearance.
Answer by stjimmy96 · Apr 01, 2016 at 12:26 PM
I figured out a way to do it. I didn't notice RaycastHit has a propriety called Transform which returns the transform of the Collider that has been hit. So I used RaycastHit hit;
//r is a Ray from the mouse position
if (Physics.Raycast(r,out hit, 100f) {
Transform cube = hit.transform; //cube is the object
// Other stuff...
}
I used RaycastHit.normal to calculate which face was hit.
Your answer
Follow this Question
Related Questions
Disable Damage Raycast? 1 Answer
Why isn't my ray working? 1 Answer
Need help with 2d shooting with raycast 0 Answers
Need help changing material back when raycast no longer hitting object. 1 Answer
Placing Object When in Certain Area? 0 Answers