I can’t get collision detection to work in Allegro 5 C++

  allegro, allegro5, c++, collision-detection

Help! I’m losing my mind trying to get collision detection to work for my Breakout clone. If anyone knows how to work with Allegro 5, be sure to pitch in with some help. This snippet is the bad code:

for (POS i = 0; i < layout[0].getBrickSize(); i++) { // Loop over bricks
        if (b.getYPos() <= layout[0].getBrick(i).getBottom() - b.getYSpeed() && b.getBottom() >= layout[0].getBrick(i).getYPos() - b.getYSpeed()) { // Vertical collision detection
            if (b.getXPos() <= layout[0].getBrick(i).getRightSide() && b.getRightSide() >= layout[0].getBrick(i).getXPos()) { // Horizontal
                // Insert sound effect here
                layout[0].eraseBrick(i); // Delete the brick that got hit
                b.reverseYSpeed(); // Bounce the ball
            }
        }
    }

POS is a typedef for unsigned short. The variable b is a Ball reference object being used in a for each loop. Layout objects are containers for all the bricks, and getBrick(int) returns a brick in the array, with its argument being which one in the vector to return. The getBrickSize() function returns the size() of the brick array used in the layout. The getRightSide() and getBottom() functions are special getters for getting xPos and yPos, but return it from the respective sides by factoring in width and height variables used in game objects.

Now that you have context, here’s the problem. When bouncing the ball into a brick, the ball will 9 times out of 10 phase through the brick it should’ve hit. Whether or not it hits a brick upon impact is inconsistent, so I’m assuming it’s something to do with Allegro being stupid. The X-axis collision works fine, but the Y-axis collision is buggy. I know this because in all my trial runs, the ball never hit a brick in the wrong column. I already tried slowing the ball down to test if my ball was going so fast it never lined up with the brick, but that solved nothing. Is there something I’m missing? If you’re familiar with Allegro 5, please help.

Source: Windows Questions C++

LEAVE A COMMENT