- Home /
Aligning a hovercraft to two axis of a transform
Right now I'm trying make the hovering vehicle align itself to the road beneath it but maintain freedom of steering (think of a car going over a twisting hill - it rolls and pitches according to the surface underneath it, but the yaw depends on the direction of the craft). The game is in 3D, obviously.
I think the problem in my current code is that it doesn't account for the relative rotation of the object, only the world rotation value? I'm not sure if that makes sense.
Here is the alignment code so far (please tell me if you need to see anything else!):
if (Physics.Raycast (downRay, hit)) {
var alignment = Quaternion.Euler(hit.transform.rotation.eulerAngles.x, 0, hit.transform.rotation.eulerAngles.z);
transform.Rotate(alignment.eulerAngles * Time.deltaTime);
}
On top of this, I can't get the model for the vehicle to be properly aligned. Right now to face forward the model is rotated 270 degrees on the x axis.
If you don't want to answer but could point me to something I could read to help me understand, that would be appreciated as well! Thank you.
Answer by robertbu · Sep 27, 2014 at 09:18 PM
The typical solution to this problem is to Raycast() and get the normal of the surface. Then you can do:
var q = Quaternion.FromToRotation(transform.up, hit.normal);
transform.rotation = q * transform.rotation;
This will allow you to continue to rotate on the object's (local) 'y' while aligning with the surface. Note for what you are doing, you might want/need to sample the normal at the four corners of your craft and use the average.
After I changed the from to transform.forward because of my messed up model it works perfectly! Thank you so much! If I may, is there a simple way to make the rotation happen over time ins$$anonymous$$d of instantly? Or limit the amount of rotation that can happen per frame? If you just want to tell me the page in the script reference to read that would also be appreciated!
You can limit the speed of the rotation by doing:
var q = Quaternion.FromToRotation(transform.up, hit.normal);
q = q * transform.rotation;
transform.rotation = Quaternion.RotateTowards(transform.rotation, q, Time.deltaTime * speed);
'speed' will be in degrees per second. For an eased rotation, replace 'RotateTowards' with 'Slerp', and greatly reduce 'speed'.
Your answer
![](https://koobas.hobune.stream/wayback/20220613163920im_/https://answers.unity.com/themes/thub/images/avi.jpg)