unity右键旋转相机视角完整代码
时间: 2023-07-03 20:05:38 浏览: 191
以下是一个简单的代码示例,用于在Unity中实现通过右键旋转相机视角:
```csharp
public class CameraController : MonoBehaviour
{
public float sensitivity = 5.0f; //鼠标灵敏度
public float smoothing = 2.0f; //相机平滑度
private Vector2 mouseLook; //相机视角
private Vector2 smoothV; //相机平滑量
void Update()
{
//获取鼠标移动量
var md = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));
//乘以灵敏度
md = Vector2.Scale(md, new Vector2(sensitivity * smoothing, sensitivity * smoothing));
//使用平滑量计算相机视角
smoothV.x = Mathf.Lerp(smoothV.x, md.x, 1f / smoothing);
smoothV.y = Mathf.Lerp(smoothV.y, md.y, 1f / smoothing);
mouseLook += smoothV;
//限制相机视角
mouseLook.y = Mathf.Clamp(mouseLook.y, -90f, 90f);
//旋转相机
transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right);
transform.localRotation *= Quaternion.AngleAxis(mouseLook.x, Vector3.up);
//按下右键时锁定光标
if (Input.GetMouseButtonDown(1))
{
Cursor.lockState = CursorLockMode.Locked;
}
//松开右键时解锁光标
if (Input.GetMouseButtonUp(1))
{
Cursor.lockState = CursorLockMode.None;
}
}
}
```
这个脚本可以将相机视角沿着水平和垂直轴旋转,使用了平滑量来使相机运动更加平滑。在按下右键时锁定光标,松开右键时解锁光标。
阅读全文