2017-04-20 102 views
0

我有它被設計爲可點擊collider2d一個遊戲物體,並且我也有一個UI按鈕將跟隨而玩家移動相機,事情是,他們有時可能會重疊,並且當它們重疊時,當用戶點擊重疊區域時,我確定用戶想要點擊對象(這是通過raycast2d命中的),所以我應該防止按鈕被點擊。unity2d防止UI按鈕被點擊時raycast2d打

可點擊遊戲物體的光線投射植入該腳本如下:

private void checkTouch() 
    { 
     if (Input.touchCount > 0 || Input.GetMouseButtonDown(0)) 
     { 
      Vector2 rayPos = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, Camera.main.ScreenToWorldPoint(Input.mousePosition).y); 
      RaycastHit2D hit = Physics2D.Raycast(rayPos, Vector2.zero, 0f); 
      if (hit) 
      { 
       Debug.Log(hit.collider.gameObject + "is hit"); 
       IInputBehavior inputBehavior = hit.collider.gameObject.GetComponent<IInputBehavior>(); 
       //IInputVehavior was a self-desgined C# interface which has a `OnClick()` method. 

       if (inputBehavior != null) 
       { 
        //here we should prevent the UIButton to be clicked, but how? 

        inputBehavior.OnClick(); 
       } 
      } 
     } 
    } 

回答

0

好了,所以我在工作,所以我不能給你確切的代碼,但我可以爲您指出正確的方向。當你所做的畫布本來它應該產生一個事件系統(如在場景中的遊戲對象的地方),你需要在你想不點擊,當用戶界面是在它的遊戲對象引用此。 在你的遊戲中的對象是這樣的:

if(GetComponent<EventSystem>().IsPointerOverGameObject) { 
    // The mouse is obscured by a UI element 
} else { 
    // The mouse is not over a UI element 
} 

https://docs.unity3d.com/ScriptReference/EventSystems.EventSystem.IsPointerOverGameObject.html

+0

我的問題是如何防止UI按鈕被點擊,您引用的代碼是如何檢測,如果被點擊的UI按鈕,如果我知道你了嗎? – armnotstrong