Collide() function

I make a game - I started to make a game and I used collide(Rect,Rect); to detect if the player is hitting a block, but I can’t get away once i hit it. That my codes fault but I don’t know how to solve this… Thank you for your help?!

constexpr uint8_t playerWidth = 16, playerHeight = 16;
constexpr uint8_t blockWidth = 16, blockHeight = 16;

while (win != 1) {
  ab.clear();
  ab.drawBitmap(0, 0, MAP1, 128, 64, WHITE);
  ab.drawBitmap(x, y, player, 16, 16, WHITE);
  ab.display();
  Rect player = Rect(x, y, playerWidth, playerHeight);
  Rect block = Rect(48, 32, playerWidth, playerHeight);
  

  if (!ab.collide(player, block)) {
    if (ab.pressed(LEFT_BUTTON) && x > 0)
      x--;
    else if (ab.pressed(RIGHT_BUTTON) && x < 112)
      x++;
    else if (ab.pressed(UP_BUTTON) && y > 0)
      y--;
    else if (ab.pressed(DOWN_BUTTON) && y < 48)
      y++;
  }
}

When posting code in this forum please enclose it in markdown code tags:

Start with a line containing three backticks followed by cpp .
Insert your code starting on the following line.
On the line following you code, put another three backticks.
The backtick character is commonly on the key below the Esc key at the top left of the keyboard.

```cpp
The first line of your code
More code
The last line of your code
```

You can also copy and paste the tags above, if you wish.

I’ve done this for you in your post but please do it yourself in the future.

Once your player collides with the block,
if (!ab.collide(player, block))
will never be true, so the code to test for the buttons being pressed will never be executed.

This should be:
Rect block = Rect(48, 32, blockWidth, blockHeight);

It’s not a problem right now because the player and block widths and heights are the same but it will be if the sizes become different.

Thanks, I saw many people using it, but I didn’t knew how.

I know that so far, but how can I make it not doing so?

You’ll have to change the x or y variable so that the player is no longer colliding with the block. How you do this will depend on what’s supposed to happen when you collide. For instance, this will move the player back to the top left of the screen if it collides:

  if (!ab.collide(player, block)) {
    if (ab.pressed(LEFT_BUTTON) && x > 0)
      x--;
    else if (ab.pressed(RIGHT_BUTTON) && x < 112)
      x++;
    else if (ab.pressed(UP_BUTTON) && y > 0)
      y--;
    else if (ab.pressed(DOWN_BUTTON) && y < 48)
      y++;
  }
  else
  {
    x = 0;
    y = 0;
  }

Ohhh, yes thats easy to make, of course I dindn’t thought of that before.
Thank you!

1 Like