- Home /
Get forward direction of face hitted by Raycast.
Hi all. I want to get forward direction (Vector3) of face, that I hitted by Raycast. Like transform.forward but not forward of transform but forward of face (or tris). I'm using C#. If you need additional info, please ask.
EDIT2: What I mean by 'face forward'. Ex.: When You select Transform on scene (and have axis selected on 'Local'), You see blue arrow indicating Z axis - object forward. I need the same but for face.
EDIT1: Here is some code, hope that will give you better look at what i need.
RaycastHit hit;
Ray ray;
Transform t;
void Update()
{
if(Input[...])
{
if(Physics.Raycast(ray, out hit, 100))
{
clone = Intantiate(t, hit.point, Quaternion.identity)
clone.LookAt(HERE I NEED FORWARD DIRECTION OF FACE);
}
}
}
Thanks in advance, Paul
Answer by robertbu · Jan 08, 2014 at 04:53 PM
You don't provide your code, so I'm unsure of what info you need. In order to find the direction of the face, you need to use a form of Raycast() that takes a RaycastHit parameter. Then you can use the RaycastHit.normal to find the normal to the face. Depending on what you define as 'forward' you may need to negate the value.
Hi, edited question with code. Hope that gives you better look. One more q: do I have to specify hitted face to use RaycastHit.normal? Or it's automatically recognize face that Raycast hit?
There are a number of problems with the code you posted, but I get the general idea. Transform.LookAt() takes a position in 3D space. For your use here, you can use Quaternion.LookRotation().
Intantiate(t, hit.point, Quaternion.LookRotation(hit.normal));
If for some reason you wanted to use LookAt(), you could do it this way:
clone.LookAt(transform.position + hit.normal);
Or you can assign the rotation:
clone.rotation = Quaternion.LookRotation(hit.normal);
Both of these assume you want to look away from the face. If you want to look towards the face, negate hit.normal.
Final note, both LookAt() and LookRotation() have an optional second parameter that defines 'up' for the rotation. Depending on how you are using this code, you may need this second parameter.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
How to Instantiate a prefab on the surface of a curved structure or mesh 1 Answer
Door only opening once on Raycast 1 Answer
Modify mesh problems 1 Answer