Unity 3D 摄像机平滑跟随

效果图.gif:

脚本代码: 

using UnityEngine;

public class CameraFollow : MonoBehaviour {

    public Transform Player;
    [Range(0.01f, 1.0f)]
    public float FollowSpeed;   //跟随速度
    [Range(0.01f, 5.0f)]
    public float Distence;
    public Vector3 RelativePos; //镜头位置偏移
    public Vector3 RelativeRot; //镜头角度偏移
    private readonly float PI = 3.1416f;

    void LateUpdate() {
        //角度跟随
        Vector3 Pos = new Vector3(transform.localEulerAngles.x, Player.localEulerAngles.y, 0);
        transform.localEulerAngles = Pos + RelativeRot;
        //位置跟随
        float delt = Player.localEulerAngles.y * PI / 180;
        float deltz = Player.localEulerAngles.x * PI / 180;
        Vector3 DeltPosition = new Vector3(-Distence * Mathf.Sin(delt) * Mathf.Cos(deltz), Distence * Mathf.Sin(deltz), -Distence * Mathf.Cos(delt) * Mathf.Cos(deltz));
        Vector3 SmoothCameraPosition = Player.position + DeltPosition - transform.position + RelativePos;
        transform.position += SmoothCameraPosition * FollowSpeed;
    }
}                                                                                                                                                                                                   

然后把要被跟随的对象拖到其Player变量里即可。

 

你可能感兴趣的:(C#和unity)