Unity实现使用鼠标实现旋转Camera的功能
在之前的项目中,公司设计提出一个需求,就是使用鼠标控制场景中Camera旋转的功能,当时因为时间比较急,我就说这个功能暂时不开发,使用按钮控制Camera的旋转。后来经过我在网上查阅相关的资料,发现网上有很多这样的案例,于是我在后来不忙的时候把这个功能给补上了。在这里做下记录,多多积累。具体实现方法如下所示:
实现步骤
1.新建一个场景,如下图所示:
2.编写CameraMovieManager.cs脚本,该脚本的作用是实现鼠标控制Camera旋转的功能,代码如下所示:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UIManager;
public class CameraMovieManager : MonoBehaviour
{
float _rotationX;
float rotationY;
public float sensitivityHor = 5.0f;
public float sensitivityVert = 5.0f;
public float minimumVert = -45.0f;
public float maximumVert = 45.0f;
//是否可以控制旋转
public bool CanControl = false;
// Update is called once per frame
void Update()
{
CameraRot();
}
void CameraRot()
{
if (CanControl)
{
//点击鼠标右键旋转摄像头
if (Input.GetMouseButton(1))
{
rotationY = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityHor;
_rotationX -= Input.GetAxis("Mouse Y") * sensitivityVert;
_rotationX = Mathf.Clamp(_rotationX, minimumVert, maximumVert);
transform.localEulerAngles = new Vector3(_rotationX, rotationY, 0);
}
}
}
3.将该脚本挂载到场景中的Camera上,运行场景,将脚本上的 Control打上勾,发现使用鼠标右键可以控制Camera旋转了,如下图所示: