Unity 鼠标控制第一人称摄像机视角

第一人称摄像机的实现:

鼠标的移动时的水平距离将决定摄像机在水平方向上的旋转角度,绕着旋转的轴应该为世界坐标系下的y轴

垂直方向上的距离将使摄像机上下旋转,这时候应该绕着自身坐标系下的x轴旋转

为什么不是绕着摄像机的x轴(transform.right),自己改了旋转的轴运行一下就知道了

public class FirstPersonalCamera : MonoBehaviour {
    public float speed = 5;
	// Update is called once per frame
	void Update () {
        //鼠标在这一帧移动的水平距离
        float x = Input.GetAxis("Mouse X");
        //绕世界坐标中的y轴旋转
        transform.Rotate(Vector3.up * x * speed, Space.World);
        //鼠标在这一帧移动的垂直距离
        float y = Input.GetAxis("Mouse Y");
        //绕自身的x轴转
        transform.Rotate(Vector3.right * -y * speed);
	}
}

 实现鼠标点击时,移动鼠标使得摄像机视角围绕主角旋转

public class CameraView : MonoBehaviour {
    Transform Player;
    private float x, y;
    public float rotateSpeed=5;
	// Use this for initialization
	void Awake() {
        Player = GameObject.FindGameObjectWithTag("Player").transform;
        //摄像机注视玩家
        transform.LookAt(Player);
	}
	// Update is called once per frame
	void Update () {
        if (Input.GetMouseButton(1))
        {
            //鼠标在这一帧移动的水平距离
            x = Input.GetAxis("Mouse X");
            //绕着玩家所在的点,世界的y轴旋转
            transform.RotateAround(Player.position, Vector3.up, x*rotateSpeed);
            //鼠标在这一帧移动的垂直距离
            y = Input.GetAxis("Mouse Y");
            //绕着玩家所在的点,摄像机的x轴旋转
            transform.RotateAround(Player.position, transform.right, y * rotateSpeed);
        }
	}
}
发布了107 篇原创文章 · 获赞 31 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/love_phoebe/article/details/102813849