Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Have a look at our Games Focus blog post series which will show what Unity is doing for all game developers – now, next year, and in the future.
    Dismiss Notice

Question Align object to normal(raycast) - weird rotation bug

Discussion in 'Scripting' started by Der_Kevin, Sep 27, 2022.

  1. Der_Kevin


    Jan 2, 2013
    hey, i am currently working on a little treehouse builder and got some problems with aligning the wooden planks to the tree normals.

    to get the normals, i do a very simple raycast - i dont think there is anything wrong with it, just for the record:
    Code (CSharp):
    2. if (Physics.Raycast(from, dir, out hit, Mathf.Infinity, _treeLayer))
    3.         {
    5.                 hitpoint = hit.point;
    6.                 hitnormal = hit.normal;
    7.                 hitobject = hit.transform.gameObject;
    8.                 Debug.DrawRay(from, dir,;
    10.         }
    and to rotate the blue object to the nomrals, i do this:

    Code (CSharp):
    1.   var newRot = Quaternion.LookRotation(Vector3.ProjectOnPlane(Vector3.up, hitnormal), hitnormal);
    2.  _objectToPlaceRoot.transform.rotation = Quaternion.Slerp(_objectToPlaceRoot.transform.rotation, newRot, RotationSpeed * Time.deltaTime);
    this is how it looks like:


    the problem is, that the Y rotation of the blue plank, should remain like how it was on the main tree, when it goes over to the horizontal tree part, it flips, that should not happen. any idea how?


    edit. i tried it with

    Code (CSharp):
    1.   var newRot = Quaternion.FromToRotation(_objectToPlaceRoot.transform.up, hit.normal) * _objectToPlaceRoot.transform.rotation;
    2. _objectToPlaceRoot.transform.rotation = Quaternion.Slerp(_objectToPlaceRoot.transform.rotation, newRot, RotationSpeed * Time.deltaTime);
    and its better. i dont get the same angle when i switch to another tree branch but... its getting there

    Last edited: Sep 27, 2022
  2. Kurt-Dekker


    Mar 16, 2013
    Pretty sure it will be the same process you use for a character controller that walks around a small globe / planet: You actually keep the previous rotation of the object and mutate it with another rotation rather than replace it.

    Specifically look at this line in

    Code (csharp):
    1. body.rotation = Quaternion.FromToRotation(localUp,gravityUp) * body.rotation;
    to see what I mean about taking current rotation and morphing it.

    In this video and source code:

    Der_Kevin likes this.