Align object to normal(raycast) - weird rotation bug

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:

if (Physics.Raycast(from, dir, out hit, Mathf.Infinity, _treeLayer))
        {

                hitpoint = hit.point;
                hitnormal = hit.normal;
                hitobject = hit.transform.gameObject;
                Debug.DrawRay(from, dir, Color.red);
       
        }

and to rotate the blue object to the nomrals, i do this:

  var newRot = Quaternion.LookRotation(Vector3.ProjectOnPlane(Vector3.up, hitnormal), hitnormal);
 _objectToPlaceRoot.transform.rotation = Quaternion.Slerp(_objectToPlaceRoot.transform.rotation, newRot, RotationSpeed * Time.deltaTime);

this is how it looks like:

8468819--1125302--ezgif-1-9132836fe0.gif

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?

thanks!

edit. i tried it with

  var newRot = Quaternion.FromToRotation(_objectToPlaceRoot.transform.up, hit.normal) * _objectToPlaceRoot.transform.rotation;
_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

8468819--1125314--ezgif-3-616aa977e9.gif

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 GravityAttractor.cs:

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:

https://www.youtube.com/watch?v=TicipSVT-T8

1 Like