2013-03-18 80 views
0

我有2個gui紋理。在GUI紋理上檢測觸摸

根據屏幕寬度和高度,我把它放在gui中。

一個用於操縱桿,另一個用於射手。

現在觸摸射手遊戲杆移動到該特定部分。

我用rect.Contains。

void Start() { 
xx = Screen.width - Screen.width/12; 
yy = Screen.height - Screen.height/8; 
lb = Screen.width/10; 
rect = new Rect(-xx/2, -yy/2, lb, lb); 
shooter.pixelInset = rect;  
shooter.enabled = false;  
} 

void OnGUI(){ 
if(characterScript.playbool){ 
    shooter.enabled = true; 
} 
if (rect.Contains(Event.current.mousePosition)){ 
shootBool = true; 
print("shoot"); 
alert.text="shoot"; 
} 
} 

對我來說工作不正常。認爲空間座標不同於gui座標。如何解決這個問題。任何人都可以建議其他好方法

回答

1

你可以試試HitTest

function Update() 
{ 
    for (var touch : Touch in Input.touches) 
    { 
     if (rect.Contains(touch.position)) 
     { 
      // we are now in the guitexture 'rect' 
      Debug.Log("rect touched"); 
      exit; 
     } 
    } 
} 

上面的代碼與觸摸一起使用,就像你在你的問題中描述的那樣。但是,由於您標記了mouse,我不確定您是否使用鼠標或觸摸。

所以,如果你用鼠標點擊的對象,你可以使用:

if (rect.Contains(Input.mousePosition) && Input.GetMouseButtonDown(0)) 
{ 
    Debug.Log("rect clicked"); 
    exit; 
} 
+1

獲取錯誤錯誤CS1061:類型'UnityEngine.Rect'不包含'HitTest'的定義,並且沒有找到'UnityEngine.Rect'類型的擴展方法'HitTest'(你是否缺少using指令或程序集參考?) – Sona 2013-03-18 10:14:39

+0

哦,原諒我,只適用於GUI元素。你可以試試'rect.Contains(touch.position)'! – Joetjah 2013-03-18 10:33:19

+0

我編輯了我的答案以反映這一點。 – Joetjah 2013-03-18 10:33:43

0

你的代碼的一些調試帶來了一些問題。

說屏幕分辨率是800x600px:

xx = 800 - 800/12 
    = 733.3333333333333 
yy = 600 - 600/8 
    = 525 
lb = 800/10 
    = 80 
rect = (-366.665, -262.5, 80, 80) 

爲什麼lb與屏幕寬度除以10確定的?

現在問題的心臟是Event.mousePosition開始在左上角的屏幕,而GUITexture.pixelInset是總部設在屏幕的中央。

您將不得不調整Event.mousePosition以使用屏幕中心作爲原點,否則您將不得不調整rect變量以從屏幕左上角開始。