简体   繁体   English

如何在 Box2D 中收到有关对象碰撞和对象触发的通知?

[英]How do I can I get notified of an object collision and object trigger in Box2D?

Unity3D has the OnCollisionEnter2D , OnCollisionExit2D , OnTriggerEnter2D etc. However, I am using Box2D and am looking for a way to implement something similar or the same in my C++ project, but I do not know how. Unity3D 具有OnCollisionEnter2DOnCollisionExit2DOnTriggerEnter2D等。但是,我正在使用 Box2D 并正在寻找一种方法来在我的 C++ 项目中实现类似或相同的东西,但我不知道如何。 I saw something about implementing a listener but I believe it was for the whole world.我看到了一些关于实现监听器的东西,但我相信它适用于整个世界。 I am looking to report these events only to the code that physics body is attached to.我希望仅将这些事件报告给物理主体所附加的代码。

Enabling an event listener is necessary for collision events in Box2D, as explained in this video . Box2D 中的碰撞事件需要启用事件侦听器,如本视频中所述。 Alternatively , you could implement your own collision logic.或者,您可以实现自己的碰撞逻辑。 For rectangular hitboxes, that would look something like this: ( Please note: this only works for rectangles with no rotation relative to the screen. )对于矩形碰撞框,看起来像这样:(请注意:这仅适用于相对于屏幕没有旋转的矩形。

if (rect1.x < rect2.x + rect2.w &&
    rect1.x + rect1.w > rect2.x &&
    rect1.y < rect2.y + rect2.h &&
    rect1.h + rect1.y > rect2.y) 
{
    // collision detected
} 
else 
{
    // no collision
}

For circles, that would look something like this:对于圆圈,看起来像这样:

auto dx = (circle1.x + circle1.radius) - (circle2.x + circle2.radius);
auto dy = (circle1.y + circle1.radius) - (circle2.y + circle2.radius);
auto distance = sqrt(dx * dx + dy * dy);

if (distance < circle1.radius + circle2.radius) 
{
    // collision detected
}
else 
{
    // no collision
}

You can see these detection algorithms in more detail here .您可以在此处更详细地查看这些检测算法。

Accoring to the api doc , OnCollisionEnter2D is bind to the object itself, so it meet your needs.根据 api docOnCollisionEnter2D绑定到对象本身,因此它可以满足您的需求。

Simply, you can add collision detection code in the ego object and do something when a collision is detected.简单地说,您可以在自我对象中添加碰撞检测代码,并在检测到碰撞时执行一些操作。

class Car {

  void process() {
    if (checkCollision(box2d)) {
      // do something
    }
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM