OnMouseDown()只调用最重要的GameObject

时间:2016-02-13 15:39:58

标签: c# unity3d unity5 unity3d-2dtools

example of situation

我有一个BoxCollider2D组件和一个附加到黑色和红色框的脚本。每个脚本都有一些在OnMouseDown()函数中发生的事情。问题是如果我点击橙色框的与黑色框重叠的部分,将调用黑框的OnMouseDown(),但我只想调用橙色框函数。

你是如何实现这一目标的?

1 个答案:

答案 0 :(得分:1)

我不认为OnMouseDown在这里是一个很好的方法。您可以使用2D RayCast来获得最顶级的对撞机。您将不得不考虑使用此方法自行排序图层和排序顺序。

检查2D中的单个点的技巧是不给出如下所示的光线投射方向:

Physics2D.Raycast(touchPostion, Vector2.zero);

这是一个我扔在一起的例子,它没有考虑使用排序图层,只是排序顺序。

using UnityEngine;

public class RayCastMultiple : MonoBehaviour 
{
    //Current active camera
    public Camera MainCamera;

    // Use this for initialization
    void Start () 
    {
        if(MainCamera == null)
            Debug.LogError("No MainCamera");
    }

    // Update is called once per frame
    void FixedUpdate () 
    {
        if(Input.GetMouseButtonDown(0))
        {
            var mouseSelection = CheckForObjectUnderMouse();
            if(mouseSelection == null)
                Debug.Log("nothing selected by mouse");
            else
                Debug.Log(mouseSelection.gameObject);
        }
    }

    private GameObject CheckForObjectUnderMouse()
    {
        Vector2 touchPostion = MainCamera.ScreenToWorldPoint(Input.mousePosition);
        RaycastHit2D[] allCollidersAtTouchPosition = Physics2D.RaycastAll(touchPostion, Vector2.zero);

        SpriteRenderer closest = null; //Cache closest sprite reneder so we can assess sorting order
        foreach(RaycastHit2D hit in allCollidersAtTouchPosition)
        {
            if(closest == null) // if there is no closest assigned, this must be the closest
            {
                closest = hit.collider.gameObject.GetComponent<SpriteRenderer>();
                continue;
            }

            var hitSprite = hit.collider.gameObject.GetComponent<SpriteRenderer>();

            if(hitSprite == null)
                continue; //If the object has no sprite go on to the next hitobject

            if(hitSprite.sortingOrder > closest.sortingOrder)
                closest = hitSprite;
        }

        return closest != null ? closest.gameObject : null;
    }

}

这只是我在这里的答案的重复:Game Dev Question