unity 鼠标右键旋转视角完整代码
时间: 2023-07-03 18:05:34 浏览: 325
以下是一个简单的 Unity 脚本,它允许你使用鼠标右键旋转视角:
```csharp
using UnityEngine;
public class CameraController : MonoBehaviour
{
public float sensitivity = 100f;
public Transform playerBody;
float xRotation = 0f;
void Update()
{
if (Input.GetMouseButton(1))
{
float mouseX = Input.GetAxis("Mouse X") * sensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime;
xRotation -= mouseY;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
playerBody.Rotate(Vector3.up * mouseX);
}
}
}
```
在这个脚本中,我们定义了一个 `sensitivity` 变量来控制旋转的速度。我们还定义了一个 `playerBody` 变量,它用于在旋转视角时旋转玩家对象。
在 `Update` 中,我们检查鼠标右键是否被按下。如果是,我们获取鼠标的移动量,并将其应用于 `xRotation` 和 `playerBody` 的旋转当中。我们还使用 `Mathf.Clamp` 来确保 `xRotation` 的值在 -90 到 90 之间,以避免玩家的头部翻转。最后,我们使用 `Quaternion.Euler` 和 `Vector3.up` 来旋转摄像机本身。
请注意,这只是一个简单的示例代码,你需要根据你的需求进行修改。
阅读全文
相关推荐
















