How to rotate an object so it always faces up?


I have a road tool that when I click and release the mouse button it creates the mesh and rotates it so the road starts and ends where the mouse events occurred. However, when I build a road on a hill one of the axis when doing this rotation always gets messed up.

alt text

I want the road to always face up, which as you can see on the pic it is facing to the side a bit.

I have tried everything I could gather for 1 week and nothing seems to work.

Code that im using in the picture to rotate:

road.transform.rotation = Quaternion.FromToRotation(Vector3.right, end - origin);

I have also tried the Rotate() method:

float angle = Vector3.Angle(Vector3.right,  end - origin);
road.transform.Rotate(Vector3.up, angle, Space.World);

I tried to get the angle between the current up and Vector3.up but I was getting garbage don’t know why.

And many more but nothing works, I’m getting frustrated with this.

Can someone assist me please?

The easiest solution would be to construct your road so that it runs forward rather than right, and that up is up. Then you use a Raycast to get the normal of the surface. The rotation code could be:

transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal) * transform.rotation;
transform.rotation = Quaternion.LookRotation(end - origin, hit.normal);

If this setup does not work for you for some reason, there are other ways to solve this problem.