Raycast Normal. Rotation Alignment.

Discussion in 'Scripting' started by NinjaTaco, Oct 26, 2010.

  1. NinjaTaco

    NinjaTaco

    Joined:
    Apr 21, 2009
    Messages:
    175
    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.
     
  2. NinjaTaco

    NinjaTaco

    Joined:
    Apr 21, 2009
    Messages:
    175
    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?


     
  3. Jesse Anders

    Jesse Anders

    Joined:
    Apr 5, 2008
    Messages:
    2,857
    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.
     
  4. NinjaTaco

    NinjaTaco

    Joined:
    Apr 21, 2009
    Messages:
    175
    Is there a simple script example that I could see that could illustrate this better?
     
  5. Jesse Anders

    Jesse Anders

    Joined:
    Apr 5, 2008
    Messages:
    2,857
    It would most likely look something like this:

    Code (csharp):
    1. transform.rotation = Quaternion.FromToRotation(transform.up, normal) * transform.rotation;
    Can't guarantee I got that exactly right, but it should be something like that.