【问题标题】:Unity 2D Collision DetectionUnity 2D 碰撞检测
【发布时间】:2015-10-01 03:53:20
【问题描述】:

我最近开始在 Unity 中开发我的第一个 2D 游戏,但遇到了碰撞检测问题。有没有简单的方法来获得侧面的碰撞检测?我的对象有一个Rigidbody2D 和一个BoxCollider2D

【问题讨论】:

    标签: c# unity3d box2d collision-detection


    【解决方案1】:

    Unity OnCollisionEnter2D 方法为您提供了对与您的游戏对象接触的对撞机的引用。因此,您可以将游戏对象的位置与击中您的游戏对象的位置进行比较。例如:

    void OnCollisionEnter2D(Collision2D coll) 
    {
        Vector3 collPosition = coll.transform.position;
    
        if(collPosition.y > transform.position.y)
        {
            Debug.Log("The object that hit me is above me!");
        }
        else
        { 
            Debug.Log("The object that hit me is below me!");
        }
    
        if (collPosition.x > transform.position.x)
        {
            Debug.Log ("The object that hit me is to my right!");
        } 
        else 
        {
            Debug.Log("The object that hit me is to my left!");
        }
    }
    

    【讨论】:

      【解决方案2】:

      假设你的对象是 A,而刚刚撞到你的对象的东西是 B。

      就像 James Hogle 所说,您应该在 A 自己的坐标系中使用 B 和 A 之间的比较位移。但是,如果您的对象被旋转,会发生什么?你需要transform.InverseTransformPoint。然后检查对撞机的象限。

      void OnCollisionEnter2D(Collision2D coll) {
          Vector3 d = transform.InverseTransformPoint(coll.transform.position);
          if (d.x > 0) {
            // object is on the right
          } else if (d.x < 0) {
            // object is on the left
          }
          // and so on
      }
      

      但是,仍然存在一个问题:更准确地说,我们应该检查碰撞的接触点。您应该使用coll.contacts 属性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-15
        • 1970-01-01
        • 2011-06-23
        • 1970-01-01
        相关资源
        最近更新 更多