Search code examples
c++visual-studioeventsgame-enginebox2d

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


Solution

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