简体   繁体   中英

How to rotate the camera smoothly in Unity?

I have a 3D car game where the camera is pointing from top to bottom. When the car moves, I need that the camera follows it. I know how to do the position following, but I don't know how to make the same rotation as for the car smoothly. I need only to change the y axis. x = 90 and z = 0 all the time. The car rotates also only on y axis.

public float interpVelocity;
public float minDistance;
public float followDistance;
public GameObject target;
public Vector3 offset;
Vector3 targetPos;

// Use this for initialization
void Start()
{
    targetPos = transform.position;
}

// Update is called once per frame
void FixedUpdate()
{
    if (target)
    {
        Vector3 posNoZ = transform.position;
        posNoZ.z = target.transform.position.z;

        Vector3 targetDirectionZ = (target.transform.position - posNoZ);

        interpVelocity = targetDirectionZ.magnitude * 5f;

        targetPos = transform.position + (targetDirectionZ.normalized * interpVelocity * Time.deltaTime);

        transform.position = Vector3.Lerp(transform.position, targetPos + offset, 0.25f);


        Vector3 posNoX = transform.position;
        posNoX.x = target.transform.position.x;

        Vector3 targetDirectionX = (target.transform.position - posNoX);

        interpVelocity = targetDirectionX.magnitude * 5f;

        targetPos = transform.position + (targetDirectionX.normalized * interpVelocity * Time.deltaTime);

        transform.position = Vector3.Lerp(transform.position, targetPos + offset, 0.25f);
    }
}

Maybe Mathf.Lerp can be helpful in your case. Lerp for angles works the same as Vector's lerp but also keeps in mind correct values, when wrapping anround 360 degrees. If you want to keep x and z axis the same all the time, your angle calculation will look like:

var currentAngle = new Vector3( 90.0f,
         Mathf.LerpAngle(currentAngle.y, targetAngle.y, Time.deltaTime), 0.0f);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM