Search code examples
c++collision-detectiongame-enginecollisionrect

Rectangle collision (C++)


I'm currently using this collision code:

( // tx = other x, tex = other end x etc.
( // horizontal collision
(xpos >= tx && xpos <= tex)
||
((xpos + w) <= tex && (xpos + w) >= tx)
)
&&
( // vertical collision
(ypos >= ty && ypos <= tey)
||
((ypos + h) <= tey && (ypos + h) >= ty)
)
)

However, it only detects if the top left pixel, the top right pixel, the bottom left pixel, or the bottom right pixel is within the rectangle to test. I don't know what to do, it already took forever to get to the current collision testing method I'm using, what can I change to fix this problem?


Solution

  • Do I understand correctly that one rectangle extends horizontally from xpos to xpos + w and vertically from ypos to ypos + h, and the other extends horizontally from tx to tex and vertically from ty to tey? With w, h, textx, and teyty all being positive?

    If so, then you can write:

    xpos <= tex && xpos + w >= tx       // horizontal collision
    && ypos <= tey && ypos + h >= ty    // vertical collision
    

    Alternatively, you may find it easier to reason about if you calculate the conditions whereby they don't collide, and just add a !:

    !(
        xpos > tex             // first rectangle entirely to right of second
        || xpos + w < tx       // first rectangle entirely to left of second
        || ypos > tey          // first rectangle entirely above second
        || ypos + h < ty       // first rectangle entirely below second
    )
    

    (The two versions are equivalent, due to one of De Morgan's laws.)