在UI上拖放

时间:2016-07-11 09:31:33

标签: c# unity3d

我想使用Unity UI对象创建一个简单的拖放游戏。

我的对象现在是附有脚本的图像。我的脚本正在使用OnBeginDragOnDragOnEndDrag事件,当我想移动图像对象时,这些事件可以正常工作。

然而,图像对象总是方形的,我只想在鼠标位于特定区域时检测拖动。所以我在我的图像上创建了一个Polygon Collider 2D并将其调整为我想要的形状。不幸的是,我无法让它发挥作用。

public void OnBeginDrag(PointerEventData eventData)
{
    var canvas = FindInParents<Canvas>(gameObject);

    itemBeingDragged = gameObject;
    m_DraggingPlane = canvas.transform as RectTransform;
}

public void OnDrag(PointerEventData eventData)
{
    SetDraggedPosition(eventData);
}

public void OnEndDrag(PointerEventData eventData)
{
    itemBeingDragged = null;
    int i = 0;
    foreach (Vector3 hex in otherHexes)
    {
        Vector3 rayBeginning = hex + transform.position;
        rays = Physics2D.RaycastAll(rayBeginning, Vector2.zero);


        if (rays.Length > 1)                                                                                //if there are other elements in RayCast
        {
            foreach (RaycastHit2D ray in rays)
            {
                if (ray.transform.gameObject != gameObject && ray.transform.tag == "Hex")                    //if element is not self and is a HexGrid
                {
                    SuccessfulDrag(ray, i);
                }
                else if (ray.transform.gameObject != gameObject && ray.transform.tag == "GetOut")            //if element is not self and is another puzzle
                {
                    FailedDrag();
                    break;
                }
            }
        }
        else if (rays.Length == 1 && rays[0].transform.gameObject == gameObject)                             //if there is only one element and it's self
        {
            FailedDrag();
            break;
        }
        i++;
    }
}

1 个答案:

答案 0 :(得分:0)

好的,我google了一下,我找到了解决方案。只需在里面创建一个包含此代码的类,并将其放在要通过它的对撞机拖动的对象上。

使用UnityEngine;

[RequireComponent(typeof(RectTransform), typeof(Collider2D))]
public class Collider2DRaycastFilter : MonoBehaviour, ICanvasRaycastFilter
{
Collider2D myCollider;
RectTransform rectTransform;

void Awake()
{
    myCollider = GetComponent<Collider2D>();
    rectTransform = GetComponent<RectTransform>();
}

public bool IsRaycastLocationValid(Vector2 screenPos, Camera eventCamera)
{
    var worldPoint = Vector3.zero;
    var isInside = RectTransformUtility.ScreenPointToWorldPointInRectangle(
        rectTransform,
        screenPos,
        eventCamera,
        out worldPoint
    );
    if (isInside)
        isInside = myCollider.OverlapPoint(worldPoint);
    return isInside;
}
}