Unity 摄像机跟随鼠标移动
时间: 2023-05-26 12:02:30 浏览: 97
本文将介绍如何使用Unity实现摄像机跟随鼠标移动的效果。
1. 创建一个新的场景,将一个摄像机放置在场景中。
2. 在Hierarchy面板中创建一个空物体,并将其命名为“CameraHolder”。
3. 将摄像机作为“CameraHolder”的子对象。
4. 将“CameraHolder”物体的Transform组件的Rotation属性重置为(0, 0, 0)。
5. 创建一个新的C#脚本,并将其命名为“CameraController”。
6. 将脚本挂载到“CameraHolder”物体上,并打开脚本进行编辑。
7. 在脚本中添加以下变量:
public float sensitivity = 5.0f;
public float maxYAngle = 80.0f;
private Vector2 currentRotation;
其中,sensitivity 表示鼠标灵敏度,maxYAngle 表示摄像机运动的最大角度,currentRotation 是记录当前摄像机的旋转角度。
8. 在Update函数中添加以下代码:
float mouseX = Input.GetAxis("Mouse X");
float mouseY = -Input.GetAxis("Mouse Y");
currentRotation.x += mouseX * sensitivity;
currentRotation.y += mouseY * sensitivity;
currentRotation.y = Mathf.Clamp(currentRotation.y, -maxYAngle, maxYAngle);
transform.eulerAngles = new Vector2(currentRotation.y, currentRotation.x);
代码解释:首先获取鼠标的X和Y轴移动距离,将其乘上鼠标灵敏度,然后累加到currentRotation变量中。同时限制当前Y轴旋转角度在-maxYAngle到maxYAngle之间。最后使用transform.eulerAngles将摄像机的角度设置为currentRotation变量的值。
9. 保存脚本并返回Unity编辑器。点击运行按钮,鼠标移动可以看到摄像机跟随鼠标移动了。
代码如下:
using UnityEngine;
public class CameraController : MonoBehaviour
{
public float sensitivity = 5.0f;
public float maxYAngle = 80.0f;
private Vector2 currentRotation;
void Update()
{
float mouseX = Input.GetAxis("Mouse X");
float mouseY = -Input.GetAxis("Mouse Y");
currentRotation.x += mouseX * sensitivity;
currentRotation.y += mouseY * sensitivity;
currentRotation.y = Mathf.Clamp(currentRotation.y, -maxYAngle, maxYAngle);
transform.eulerAngles = new Vector2(currentRotation.y, currentRotation.x);
}
}
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)