简体   繁体   English

如何在Unity中平稳旋转相机?

[英]How to rotate the camera smoothly in Unity?

I have a 3D car game where the camera is pointing from top to bottom. 我有一个3D汽车游戏,摄像头从顶部指向底部。 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. 我只需要更改y轴。 x = 90 and z = 0 all the time. x = 90z = 0一直。 The car rotates also only on y axis. 汽车也仅在y轴上旋转。

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. 也许Mathf.Lerp在您的情况下会有所帮助。 Lerp for angles works the same as Vector's lerp but also keeps in mind correct values, when wrapping anround 360 degrees. 角度的Lerp与Vector的lerp相同,但在环绕360度时也要记住正确的值。 If you want to keep x and z axis the same all the time, your angle calculation will look like: 如果要始终保持x轴和z轴相同,则角度计算将如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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