- Home /
How to rotate an object so it always faces up?
Hi,
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.
Picture:
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?
Answer by robertbu · Oct 27, 2014 at 05:37 AM
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.
It didn't worked as intended, the road is now facing the normals, which is an improvement I guess.
Can you show me a picture so I can see the result? I'm confused about what you mean by 'facing the normals'.
Taking the slope of the hill is what my code does. Obvious from your comment, that is not what you want. Can you describe what you want? Given the curve of the hill and road, I cannot see a right solution unless you were to bend your road to the hill. If you just want the road facing up, you can do:
transform.rotation = Quaternion.LookRotation(end - origin, Vector3.up);
Your answer
![](https://koobas.hobune.stream/wayback/20220613170036im_/https://answers.unity.com/themes/thub/images/avi.jpg)