unity鼠标左键控制物体移动
时间: 2023-08-09 12:04:23 浏览: 207
可以通过以下代码实现鼠标左键控制物体移动:
```csharp
using UnityEngine;
public class ObjectMover : MonoBehaviour
{
public float moveSpeed = 5f; // 移动速度
void Update()
{
if (Input.GetMouseButton(0)) // 如果鼠标左键被按下
{
float mouseX = Input.GetAxis("Mouse X"); // 获取鼠标在X轴上的移动值
float mouseY = Input.GetAxis("Mouse Y"); // 获取鼠标在Y轴上的移动值
// 将鼠标移动值转换为物体移动距离
float moveAmountX = mouseX * moveSpeed;
float moveAmountY = mouseY * moveSpeed;
// 在平面上移动物体
Vector3 moveVector = new Vector3(moveAmountX, moveAmountY, 0f);
transform.Translate(moveVector, Space.Self);
}
}
}
```
将此脚本挂载到需要移动的物体上,即可通过鼠标左键控制物体移动。其中,鼠标在X轴上的移动值控制物体在X轴上的移动,鼠标在Y轴上的移动值控制物体在Y轴上的移动。
阅读全文
相关推荐


















