为什么在 Unity 中用于 2D 拖动的这段代码不起作用?
Why this code for 2D dragging in Unity doesn't work?
刚接触Unity,今天尝试实现鼠标拖动。我写了下面的代码:
void OnMouseDrag()
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint);
transform.position = curPosition;
}
然而,在拖动 GameObject 后它从相机中消失了,但我可以看到它从场景视图中的原始位置移动了。
在网上搜索了一下,发现正确的版本是这样的:
void OnMouseDown()
{
offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10));
}
void OnMouseDrag()
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
我不明白为什么需要 offset
值。为什么会有所不同?谁能给我解释一下?
谢谢!
当您拖动一个游戏对象时,您需要通过它在 OnMouseDrag 中的增量来移动它。增量是指前一帧和当前帧内的位置之间的差异。
但是在拖动开始之前当前位置是未知的,这就是为什么应该在开始拖动之前设置偏移量,即在 OnMouseDown 中。
如果您不在 OnMouseDown 中设置偏移量,则会发生两种情况:
- GameObject 靠近相机(Z 轴),您需要手动修改其 Z(这是您遇到奇怪行为的原因)。 这是因为相机在 Z 轴上的位置始终与其渲染的可见对象不同。假设相机位于
0,0,-10
并且 GameObject 位于 0,0,0
在这种情况下 Camera.main.ScreenToWorldPoint(Input.mousePosition)
将始终 return -10 在 Z 轴
- 始终将 GameObject 的中心固定在鼠标上,而不是您开始拖动的点。
注:
您现在可以将两个 Z 值从 10 更改为 0。这是因为在每一帧中都应用了偏移。
刚接触Unity,今天尝试实现鼠标拖动。我写了下面的代码:
void OnMouseDrag()
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint);
transform.position = curPosition;
}
然而,在拖动 GameObject 后它从相机中消失了,但我可以看到它从场景视图中的原始位置移动了。
在网上搜索了一下,发现正确的版本是这样的:
void OnMouseDown()
{
offset = transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10));
}
void OnMouseDrag()
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
我不明白为什么需要 offset
值。为什么会有所不同?谁能给我解释一下?
谢谢!
当您拖动一个游戏对象时,您需要通过它在 OnMouseDrag 中的增量来移动它。增量是指前一帧和当前帧内的位置之间的差异。
但是在拖动开始之前当前位置是未知的,这就是为什么应该在开始拖动之前设置偏移量,即在 OnMouseDown 中。
如果您不在 OnMouseDown 中设置偏移量,则会发生两种情况:
- GameObject 靠近相机(Z 轴),您需要手动修改其 Z(这是您遇到奇怪行为的原因)。 这是因为相机在 Z 轴上的位置始终与其渲染的可见对象不同。假设相机位于
0,0,-10
并且 GameObject 位于0,0,0
在这种情况下Camera.main.ScreenToWorldPoint(Input.mousePosition)
将始终 return -10 在 Z 轴 - 始终将 GameObject 的中心固定在鼠标上,而不是您开始拖动的点。
注:
您现在可以将两个 Z 值从 10 更改为 0。这是因为在每一帧中都应用了偏移。