2016-02-13 70 views
0

example of situationonmousedown事件()只要求最重要的遊戲對象

我有一個BoxCollider2D組件和連接到黑色和紅色方框的腳本。每個腳本在OnMouseDown()函數中發生一些事情。問題是如果我點擊與黑色框重疊的橙色框的部分,黑色框的OnMouseDown()將被調用,但我只需要調用橙色框函數。

你是如何做到這一點的?

回答

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