如何在Box2D中通知对象碰撞和对象触发器?

发布于 2025-02-12 07:28:32 字数 219 浏览 2 评论 0原文

Unity3d具有oncollisionEnter2doncollisionExit2dontriggerenter2d等。但是,我正在使用Box2D,并且正在寻找一种实现类似或同一的方法在我的C ++项目中,但我不知道如何。我看到了有关实施听众的一些东西,但我相信这是针对全世界的。我希望仅将这些事件报告给物理主体所附加的代码。

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

日暮斜阳 2025-02-19 07:28:32

此视频。 另外,您可以实现自己的碰撞逻辑。对于矩形命中箱,看起来像这样的东西:( 请注意:这仅适用于矩形,而无旋转相对于屏幕。

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
}

对于圆圈,看起来会看起来有些东西这样:

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
}

您可以更详细地看到这些检测算法在这里

Enabling an event listener is necessary for collision events in Box2D, as explained in this video. 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.

遮云壑 2025-02-19 07:28:32

api doc 到对象本身,因此满足您的需求。

简而言之,您可以在自我对象中添加碰撞检测代码,并在检测到碰撞时做某事。

class Car {

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

Accoring to the api doc, OnCollisionEnter2D is bind to the object itself, so it meet your needs.

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
    }
  }
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文