首页 > 解决方案 > unity拖拽世界位置

问题描述

我目前正在 Unity 中开发一个基本的纸牌游戏,但在弄清楚如何对我的纸牌进行拖动时遇到了一些麻烦。我目前的布局如下: 在此处输入图像描述

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

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

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

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

谢谢

编辑:

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

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

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
}

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

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

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
}

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

标签: unity3ddrag-and-drop

解决方案


因此,在玩了一些游戏并检查了我从 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);

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


推荐阅读