1. 程式人生 > >Unity3D 攝像機跟隨旋轉的方案

Unity3D 攝像機跟隨旋轉的方案

Intro

主要想探討的是如何令攝像機隨滑鼠操作進行旋轉和移動,攝像機跟隨的指令碼官方就有Example。

方案:獨立的角度變數

主要的特點是使用獨立的角度變數,每次處理滑鼠移動操作都會建立一個新的Quaternion用於計算。

先看Demo。

public class PlayerControls : MonoBehaviour
{
    public GameObject Player;
    public float Distance;
    //public float CameraRepositionSpeed;
    public float MouseMotionScaleLevel;
    public bool ReverseAxisY;
    public float PitchMaximum;
    public float PitchMinimum;
    private float _CurrentCameraAngleAroundX;
    private float _CurrentCameraAngleAroundY;
    private Vector3 _PositionTarget;

    // Use this for initialization
    void Start()
    {
    }

    // Update is called once per frame
    void Update()
    {
        _CurrentCameraAngleAroundX += Input.GetAxis("Mouse Y") * MouseMotionScaleLevel * Time.deltaTime * (ReverseAxisY ? -1 : 1);
        _CurrentCameraAngleAroundY += Input.GetAxis("Mouse X") * MouseMotionScaleLevel * Time.deltaTime;
        _CurrentCameraAngleAroundX = Mathf.Clamp(_CurrentCameraAngleAroundX, PitchMinimum, PitchMaximum);
        _PositionTarget = Player.transform.position + Quaternion.Euler(_CurrentCameraAngleAroundX, _CurrentCameraAngleAroundY, 0) * (-Player.transform.forward * Distance);

        //transform.position = Vector3.Lerp(transform.position, _PositionTarget, Time.deltaTime * CameraRepositionSpeed);
        transform.position = _PositionTarget;
        transform.LookAt(Player.transform);
    }
}

核心在於_CurrentCameraAngleAroundX_CurrentCameraAngleAroundY以及Distance,這三個變數共同決定了以玩家Player為原點的極座標系下攝像機所處的空間位置。

計算座標時只需要通過Quaternion.Euler來取得旋轉四元數,以玩家為原點衍生一條(0,0,-1)的向量並乘上四元數以旋轉至Player指向攝像機的方向,最後乘上Distance,即可得到攝像機相對玩家的偏移。

_PositionTarget = Player.transform.position +
    Quaternion.Euler(_CurrentCameraAngleAroundX, _CurrentCameraAngleAroundY, 0) *
    (-Player.transform.forward * Distance);

最後只要將攝像機放置在那個位置,然後LookAt旋轉到z軸正方向指向玩家就完事兒了。