Unity 2D 碰撞检测

Unity 2D Collision Detection

我最近开始在 Unity 中开发我的第一个 2D 游戏,但我遇到了碰撞检测问题。有什么简单的方法可以进行侧面碰撞检测吗?我的对象有一个 Rigidbody2D 和一个 BoxCollider2D.

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!");
    }
}

假设你的物体是A,刚撞到你物体的东西是B。

正如James Hogle所说,你应该在A自己的坐标系中使用B和A之间的位移比较。但是,如果旋转对象会怎样?你需要transform.InverseTransformPoint。然后查看collider的象限

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 属性.