1. Help us improve the editor usability and artist workflows. Join our discussion to provide your feedback.
    Dismiss Notice
  2. We're looking for feedback on Unity Starter Kits! Let us know what you’d like.
    Dismiss Notice
  3. We’re giving 2017.1 beta testers a chance to win t-shirts and a Nintendo Switch. Read more on the blog.
    Dismiss Notice
  4. We want to know how you learned Unity! Help us by taking this quick survey and have a chance at a $25 gift card
    Dismiss Notice
  5. Are you an artist or level designer going to Unite Europe? Join our roundtables there to discuss artist features.
    Dismiss Notice
  6. Unity 5.6 is now released.
    Dismiss Notice
  7. Check out all the fixes for 5.6 on the patch releases page.
    Dismiss Notice

Raycast Normal. Rotation Alignment.

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

  1. NinjaTaco

    NinjaTaco

    Joined:
    Apr 21, 2009
    Posts:
    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
    Posts:
    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
    Posts:
    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
    Posts:
    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
    Posts:
    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.