2013-03-18 87 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变量以从屏幕左上角开始。