unity鼠标移动视角
时间: 2024-03-16 13:38:04 浏览: 130
在Unity中,可以通过鼠标移动来改变视角。以下是一种实现方法:
```csharp
using UnityEngine;
public class CameraController : MonoBehaviour
{
public float rotationSpeed = 5f;
public float zoomSpeed = 5f;
public float panSpeed = 5f;
private Vector3 lastMousePosition;
void Update()
{
// 鼠标右键旋转视角
if (Input.GetMouseButton(1))
{
float mouseX = Input.GetAxis("Mouse X");
float mouseY = Input.GetAxis("Mouse Y");
transform.Rotate(Vector3.up, mouseX * rotationSpeed, Space.World);
transform.Rotate(Vector3.right, -mouseY * rotationSpeed, Space.Self);
}
// 鼠标滚轮缩放视角
float scroll = Input.GetAxis("Mouse ScrollWheel");
transform.Translate(Vector3.forward * scroll * zoomSpeed, Space.Self);
// 鼠标中键平移视角
if (Input.GetMouseButton(2))
{
Vector3 mouseDelta = Input.mousePosition - lastMousePosition;
transform.Translate(-mouseDelta.x * panSpeed * Time.deltaTime, -mouseDelta.y * panSpeed * Time.deltaTime, 0, Space.Self);
}
lastMousePosition = Input.mousePosition;
}
}
```
这段代码实现了通过鼠标右键旋转视角,鼠标滚轮缩放视角,鼠标中键平移视角的功能。你可以将这段代码添加到一个空物体上,并将该物体作为摄像机的父物体,然后将鼠标控制的脚本挂载到该物体上,即可实现鼠标移动视角的效果。
阅读全文