unity鼠标左键控制物体移动
时间: 2023-08-09 18:05:19 浏览: 85
你可以通过以下代码来实现在 Unity 中使用鼠标左键控制物体移动:
```csharp
public class ObjectController : MonoBehaviour
{
private Vector3 mOffset;
private float mZCoord;
private void OnMouseDown()
{
mZCoord = Camera.main.WorldToScreenPoint(gameObject.transform.position).z;
mOffset = gameObject.transform.position - GetMouseWorldPos();
}
private Vector3 GetMouseWorldPos()
{
Vector3 mousePoint = Input.mousePosition;
mousePoint.z = mZCoord;
return Camera.main.ScreenToWorldPoint(mousePoint);
}
private void OnMouseDrag()
{
transform.position = GetMouseWorldPos() + mOffset;
}
}
```
在这个代码中,我们首先在鼠标按下的时候记录下物体当前的位置和鼠标点击位置之间的偏移量。然后在鼠标拖拽的过程中,我们根据鼠标的当前位置和之前记录的偏移量计算出物体应该移动到的新位置,并将物体移动到这个新位置上。注意,在这个代码中,我们使用了 Camera.main.WorldToScreenPoint() 方法将物体的世界坐标转换为屏幕坐标,以便正确地计算出鼠标的位置。同时,我们也使用了 Camera.main.ScreenToWorldPoint() 方法将屏幕上的鼠标位置转换为世界坐标,以便正确地移动物体。
阅读全文
相关推荐















