首页 > 解决方案 > Vector3.zero 被窃听

问题描述

我有一个简单的库存系统,其中 Canvas 设置为屏幕空间 - 相机。出于某种原因,将图标设置为 vector3.zero 会使它们转到其他地方。

这是一个例子: 在此处输入图像描述

第一张图像正在启动,一切正常。

在此处输入图像描述

第二张图片是苹果被拖动,你可以看到位置是正确的

在此处输入图像描述

可以看出,一旦掉落,苹果就会去一个未知的地方。

这是 endDrag 的代码:

public void OnEndDrag(PointerEventData eventData)
{
    if (item.category != ITEM_CATEGORY.Voxel)
    {
        icon.transform.position = Vector3.zero;
    }   
    else
    {
        cube.transform.position = Vector3.zero;
    }
}

没有什么独特的。

这是拖动事件:

public void OnDrag(PointerEventData eventData)
{
    if (item.category != ITEM_CATEGORY.Voxel)
    {
        Vector3 screenPoint = Input.mousePosition;
        screenPoint.z = 0.13f; //distance of the plane from the camera
        icon.transform.position = Camera.main.ScreenToWorldPoint(screenPoint);
    }
    else
    {
        Vector3 screenPoint = Input.mousePosition;
        screenPoint.z = 0.13f; //distance of the plane from the camera
        cube.transform.position = Camera.main.ScreenToWorldPoint(screenPoint);
    }
}

标签: c#visual-studiounity3d

解决方案


您在 RectTransform 的检查器中看到的是对象的本地位置。但在代码中,您正在操纵对象的世界位置。当您将对象的世界位置设置为 (0, 0, 0) 时,它的本地位置不太可能也是 (0, 0, 0)。您的代码所做的实际上是将对象移动到游戏世界的原点。

被窃听的不是 Vector3.zero(这没有任何意义),而是您的代码。在您的OnEndDrag函数中,尝试重置对象的本地位置而不是其世界位置,如下所示:

cube.transform.localPosition = Vector3.zero;

当然是图标的同上。


推荐阅读