Raycast Normal. Rotation Alignment.

I am trying to get an axis of a cube to align itself to the normals of an object. Sounds simple enough right?

How do I get the returned normal that is hit by a raycast to be applied to the rotation of the cube so that alignment occurs?

I found these things which didn’t help.

http://answers.unity3d.com/questions/9704/instantiate-based-on-raycasthit-normal

The unity scripting manual… Which gives a vague description.

RaycastHit.normal
Description
The normal of the surface the ray hit.

I found this with some more searching… I’m not sure if this would work. (I will have to try when I get home)

I am confused as to how an angle of rotation can be calculated by looking at the normals of an object. Because I am thinking a point of reference must be used to distinguish from one degree to another degree of rotation. For calculating the angle of a normal, does unity use the world space as a reference? If not, how does unity determine the angle of rotation for surface normals?

1 Like

Short answer: Use Quaternion.SetFromToRotation() or Quaternion.FromToRotation() to compute a rotation that will rotate the cube’s current up vector onto the surface normal, and then apply it to the Transform.rotation field to align the cube.

Is there a simple script example that I could see that could illustrate this better?

It would most likely look something like this:

transform.rotation = Quaternion.FromToRotation(transform.up, normal) * transform.rotation;

Can’t guarantee I got that exactly right, but it should be something like that.