Unity 摄像机视角跟随角色移动

新建一个Capsule作为Player,创建一个cube体现人物的正反面。

 Unity 摄像机视角跟随角色移动_第1张图片

分别创建四个空物体(注意坐标清零)

 

将相机放到Zoom节点下

public class NewBehaviourScript : MonoBehaviour
{
    //控制左右旋转
    public Transform Y_Axis;
    //控制上下旋转
    public Transform X_Axis;
    //控制左右倾斜
    public Transform Z_Axis;
    //控制远近距离
    public Transform zoom_Axis;

    //玩家对象
    public Transform Player;

    //旋转速度
    public float roSpeed = 180;
    //缩放速度
    public float scSpeed = 50;
    //限定角度
    public float limiAngle = 45;

    //鼠标左右滑动数值,滚轮数值
    private float hor, ver, scrollView;
    float x = 0, sc = 10;

    //是否跟随玩家
    public bool followFlag;

    //是否控制玩家
    public bool turnFlag;

    private void LateUpdate()
    {
        //输入获取
        hor = Input.GetAxis("Mouse X");
        ver = Input.GetAxis("Mouse Y");

        //鼠标滚轮数值
        scrollView = Input.GetAxis("Mouse ScrollWheel");

        //左右滑动鼠标
        if (hor != 0)
        {
            //围绕Y轴旋转,Vector3.up是本地坐标位置
            Y_Axis.Rotate(Vector3.up * roSpeed * hor * Time.deltaTime);
        }

        //上下滑动
        if (ver != 0)
        {
            x += -ver * Time.deltaTime * roSpeed;
            x = Mathf.Clamp(x, -limiAngle, limiAngle);
            Quaternion q = Quaternion.identity;
            q = Quaternion.Euler(new Vector3(x, X_Axis.eulerAngles.y, X_Axis.eulerAngles.z));
            X_Axis.rotation = Quaternion.Lerp(X_Axis.rotation,q,Time.deltaTime*roSpeed);
        }

        //缩放远近
        if (scrollView != 0)
        {
            sc -= scrollView * scSpeed;
            sc = Mathf.Clamp(sc, 3, 10);
            zoom_Axis.transform.localPosition = new Vector3(0, 0, -sc);
        }

        //跟随玩家
        if(followFlag && Player != null)
        {
            Y_Axis.position = Vector3.Lerp(Y_Axis.position, Player.position + Vector3.up, Time.deltaTime * 10f);
        }
        //旋转玩家
        if(turnFlag && Player != null)
        {
            Player.transform.forward = new Vector3(transform.forward.x, 0, transform.forward.z);
        }
    }

}

你可能感兴趣的:(unity,游戏引擎)