【问题标题】:Unity drag and drop in world positionsunity拖拽世界位置
【发布时间】:2019-08-23 13:15:51
【问题描述】:

我目前正在使用 Unity 开发一款基本的纸牌游戏,但在弄清楚如何对我的纸牌进行拖动时遇到了一些麻烦。我目前的布局如下:

我目前正在尝试使用IDragHandler 接口在我的卡片对象上检测到拖动事件时接收回调。

我的最终目标是能够根据触摸/鼠标滑动的 x 轴向左/向右滑动卡片。

我目前尝试使用传递给 OnDrag() IDragHandler 的 eventdata.delta 值来移动我的卡,但据我所知,这个值以像素为单位,当使用 Camera.main.ScreenToWorldPoint( ) 的结果为 0,0,0。同样,尝试跟踪拖动开始的位置并减去当前位置会得到 0,0,0 的值。

我目前对如何使用世界单位拖动游戏对象有点不知所措,所以如果有人能给我一些指导,我将不胜感激。

谢谢

编辑:

^这就是为什么你不应该在深夜使用 StackOverflow。

所以要添加一些额外的上下文:

  • 卡片只是附加了网格渲染器和嵌入画布以添加文本的游戏对象(可能不是添加文本的最佳方式,但它有效)
  • 卡片都在一个“手”对象下,该对象由一个用于接收事件的盒子 collider2d 和一个实现 IBeginDragHandler、IEndDragHandler 和 IDragHandler 的脚本组成
  • 到目前为止,我已经尝试了两种不同的方法来计算拖动距离:
public void OnDrag(PointerEventData eventData)
{
    Vector2 current = Camera.main.ScreenToWorldPoint(eventData.position);
    Debug.Log("Current world position: "+current);

    Vector3 delta = lastDragPoint - current;

    // Store current value for next call to OnDrag
    lastDragPoint = eventData.position;

    // Now use the values in delta to move the cards
}

使用这种方法,我在调用 ScreenToWorldPoint 后总是得到 0,0,0 的值,所以我无法移动卡片

我尝试过的第二种方法是:

public void OnDrag(PointerEventData eventData)
{
    Vector3 screenCenter = new Vector3(Screen.width * 0.5f, Screen.height * 0.5f, 1f);
    Vector3 screenTouch = screenCenter + new Vector3(eventData.delta.x, eventData.delta.y, 0f);

    Vector3 worldCenterPosition = Camera.main.ScreenToWorldPoint(screenCenter);
    Vector3 worldTouchPosition = Camera.main.ScreenToWorldPoint(screenTouch);

    Vector3 delta = worldTouchPosition - worldCenterPosition;

    // Now use the values in delta to move the cards
}

使用这种方法,我得到了更好的结果(卡片实际上会移动),但它们不能正确地跟随鼠标。如果我拖动一张卡片,我将朝鼠标的方向移动,但是移动的距离明显小于鼠标移动的距离(即当鼠标到达屏幕边缘时,卡片只移动了一张卡片宽度)

【问题讨论】:

  • 您的卡片是 Canvas gui 对象吗?画布有什么渲染模式(屏幕空间、相机空间或世界空间?)
  • 您使用的是哪个版本的 Unity?此外,您能否提供您所说的代码不起作用?很难猜出问题出在哪里。
  • @Draco18s 没有画布,只是一个游戏对象。
  • @ErikOverflow 抱歉信息不足,帖子已被编辑。我正在使用 unity 2019.1.11(我相信是最新的非测试版)

标签: unity3d drag-and-drop


【解决方案1】:

因此,在玩了一些游戏并检查了我从 ScreenToWorldPoint 的调用中收到的各种值之后,我终于找到了问题所在。 在我第二次尝试的方法的代码中,我发现我在 ScreenToWorldPoint 中为 Z 参数使用了不正确的值。经过一番研究,我发现他应该是相机和(我猜)触摸表面之间的 Z 距离。

Vector3 screenCenter = new Vector3(Screen.width * 0.5f, Screen.height * 0.5f, -Camera.main.transform.position.z);
Vector3 screenTouch = screenCenter + new Vector3(eventData.delta.x, eventData.delta.y, 0);

感谢所有花时间阅读我的问题的人。

【讨论】:

    【解决方案2】:

    您可以使用 OnMouseDown -方法来检测玩家何时开始拖动卡片并根据鼠标位置更新其位置。当拖动结束时,调用 OnMouseUp 方法。

    https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseDown.html https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseUp.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 2019-09-09
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      相关资源
      最近更新 更多