【问题标题】:detect touch on GUI Textures检测 GUI 纹理上的触摸
【发布时间】:2013-03-06 11:08:39
【问题描述】:

我有 2 个 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 坐标不同。如何解决这个问题。任何人都可以提出任何其他好的方法

【问题讨论】:

    标签: user-interface mouse unity3d


    【解决方案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;
    }
    

    【讨论】:

    • Getting error error CS1061: Type UnityEngine.Rect' does not contain a definition for HitTest' and no extension method HitTest' of type UnityEngine.Rect' 找不到(您是否缺少 using 指令或程序集引用?)
    • 哦,对不起,这只适用于 GUI 元素。你可以试试rect.Contains(touch.position)
    • 我有 2 个按钮。一个用于射击游戏,另一个用于操纵杆。所以对于这两个我该怎么做。
    • 将上面的更新代码放在一个类中并将其附加到您的按钮上。使用上面的代码进行触摸,下面的代码用于鼠标点击。
    【解决方案2】:

    对您的代码进行一些调试会带来一些问题。

    说屏幕分辨率是800x600px:

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

    为什么lb是由屏幕宽度除以十来决定的?

    现在问题的核心是Event.mousePosition 从屏幕左上角开始,而GUITexture.pixelInset 位于屏幕中心。

    您必须调整Event.mousePosition 以使用屏幕中心作为原点,或者您必须调整rect 变量以从屏幕左上角开始。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多