- Home /
Rotate unit while taking terrain into consideration
I have vehicles in my game that need to have their y rotation value adjust based on the terrain underneath them. When driving uphill, my units y rotation will be incorrect. This is what I currently use to rotate my unit.
Quaternion rot = Quaternion.LookRotation(targetDir - unit.transform.position);
float rotateVelocity = Mathf.Min (3.0f * Time.deltaTime, 1);
unit.transform.rotation = Quaternion.Lerp(unit.transform.rotation, rot, rotateVelocity);
To visualize what I mean, here an image:
http://answers.unity3d.com/storage/temp/17661-exampleimg.png
What I effectively need to do, is to get the coordinates of the mesh of the terrain at the front of my unit, and the back, but how do I accomplish that?
You will need the info of what its colliding against to rotate angle against it, for that cast a small ray from the vehicle, at 0 Y position, probally front and back. When you get the hit info from the raycast, hit.point, would tell you the exact point where it hit. And then you can use this info to convert position to euler angles.
$$anonymous$$eep in $$anonymous$$d that the update of the vehicle should happen in LateUpdate and the RayCast should happen in Update(). SO that you can predict and respond to what the raycast tells you.
The alternative way is to apply, physics materials to the vehicles tires, and the object will be pushed outwards.
$$anonymous$$gest also looking at the Car tutorial, to see how vehicle physics is handled.
You can use this link for experimenting Raycast. Raycast info
For higher accuracy, use BarycentricCo-ordinate, although this will require mathematical knowledge.