Unity - using RayCast to orient an object to terrain (C #)

I am currently making a flight simulator. Right now, I'm trying to get the plane to fly on its own, but I'm having some trouble trying to rotate the plane so that it is parallel to the ground.

This is my code:

heightDetect = new Ray (transform.position, Vector3.down);

        if (Physics.Raycast (heightDetect, out hit, Mathf.Infinity)) {
            Debug.Log (hit.distance);

            transform.rotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation;


            Debug.DrawRay (heightDetect.origin, heightDetect.direction*1000);

        }

      

The code works and that's it, but the problem is that it's too bumpy. The camera on the airplane keeps on my screen and doesn't play completely. Is there a way to smooth this process? Thank!

+3


source to share


2 answers


Presumably, you are doing this in your function Update

and hence changing the rotation of your plane many times per second. Instead of setting rotation directly, you can use spherical linear interpolation :

public float speed = 0.1f;

void Update() {
    ...
    var targetRotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation;
    transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * speed);
}

      



This effectively smooths out the rotation over time. It works by taking the current rotation and the possible required rotation, but only returning the rotation somewhere in the middle (controlled speed

).

+1


source


If I understand correctly, you are looking for Quaternion.Lerp to smooth rotation for Quaternions, or Mathf.LerpAngle for Vector3 rotation.

Usage example:



Vector3 currentRotation = transform.rotation;
Vector3 newRotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation;
newRotation = new Vector3(
                 Mathf.LerpAngle(currentRotation.x, newRotation.x, Time.deltaTime),
                 Mathf.LerpAngle(currentRotation.y, newRotation.y, Time.deltaTime),
                 Mathf.LerpAngle(currentRotation.z, newRotation.z, Time.deltaTime));
transform.rotation = newRotation;

      

Multiply Time.deltaTime

by any value to change the "lerp" speed.

0


source







All Articles