【问题标题】:buttons only react to clicks/touches when clicking/touching to the right of them按钮仅在单击/触摸右侧时对单击/触摸做出反应
【发布时间】:2015-02-07 13:23:27
【问题描述】:

我在 Unity3D 中为 android 制作 2D 游戏。现在我正在制作按钮。并且此按钮无法正确响应点击/触摸。我对鼠标点击和触摸都有同样的问题。每个按钮都有与对象大小相同的触发 boxcollider。但是按钮只有在我点击区域时才会做出反应,这就是按钮。我不明白为什么会这样。我该怎么办?这是我的代码:

   if (Input.GetMouseButtonDown(0)) {

        Vector3 i = Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, 1));
        RaycastHit2D hit = Physics2D.Raycast (i, i);

        if (hit.transform != null) {

            if (hit.transform.tag == "button") {

                hit.transform.gameObject.SetActive(false);

            }

        }
    }

另外,我在鼠标单击“i”位置时实例化了一个对象,以检查它是否正确地将屏幕位置转换为世界,并且工作正常。

【问题讨论】:

    标签: unity3d click touch 2d mouse


    【解决方案1】:

    Physics2D.Raycast 中的第一个参数是原点,第二个参数是direction,所以你应该从ray.originray.direction 方向进行光线投射

     void Update () {
                    if (Input.GetMouseButtonDown(0)) {
                Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
                RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction, Mathf.Infinity);
                if (hit) {
                    if(hit.collider.gameObject.tag=="button"){
                       //do something
                  }
               }
            }  
         }
    

    【讨论】:

      【解决方案2】:

      尝试这样处理:

      if (Input.GetMouseButtonDown(0)) {
      
          Vector3 pos = Camera.main.ScreenToWorldPoint (Input.mousePosition);
          Vector2 touchPos = new Vector2(pos.x, pos.y);
          Collider2D hit = Physics2D.OverlapPoint(touchPos);
      
          if (hit) {
              Debug.Log(hit.transform.gameObject.name);
      
              if (hit.transform.tag == "button") {
                  hit.transform.gameObject.SetActive(false);
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-23
        • 1970-01-01
        • 2023-03-11
        • 2014-04-13
        • 1970-01-01
        • 1970-01-01
        • 2011-04-01
        • 1970-01-01
        相关资源
        最近更新 更多