# C++ Platformer Collision

This is very simple, but I have spent nearly 6 months messing with this and it is always messed up.

This is a tile platformer, everything is "normal", x and y correspond to tile. Tiles are 32 x 32 pixels.

// Get all tile numbers, top left, top right, bottom left, bottom right
int X = 63; // and in this, say the player is moving right
int Y = 50;
int Width = 33; // This is the problem, if it is < 32, the collisions are all over the place, in the open, where there shouldn't be.
int Height = 50;

int tile_x = floor( (double) X/32);
int tile_y = floor( (double) Y/32);
int tile_x2 = floor( (double) (X + Width)/ 32);
int tile_y2 = floor( (double) (Y + Height)/ 32);
bool open = true;

// This is meant to catch cases where width < 32
if (tile_x == tile_x2) {
if (IsOpenPt(tile_x, tile_y)) { return true; }
}

// loop through tiles
for (int y = tile_y; y < tile_y2; y++) {

for (int x = tile_x; x < tile_x2; x++) {

// this spot is not open
if (!IsOpenPt(x,y)) { open = false; }

}
}

return open;


This works if the width is greater than 32, but if it anything less, everything becomes random open point/ not.

See anything wrong with my formula? I have exhausted searches, nothing. Once again I emphasize, the entire project, I have been trying to get this part to work. I have literally a 100 page notebook of attempts at visualizing and grids to put it on paper.

• What space are X, Y, Width and Height in? Pixels? Is 32 your tile width in pixels? – Tyyppi_77 Apr 11 '16 at 10:17
• Tiles are 32 by 32. X and Y are the top left point of the player. The player stands on the ground (Y + Height), at X (with a width of Width.) So, with the code above, it works perfect if the width is greater than 32. If the width is less than, the entire thing breaks. By that I mean, I can not figure out what it is doing, I get very mixed results, seemingly almost random. – Evan Carslake Apr 11 '16 at 16:39
• The question as phrased is for me hard to understand. If you could structure it more like: 1. Here is a collision test method. 2. When I give it this input, I would expect the following output, "<output>". 3. But what I got instead was "<wrong output>". The code here looks like the middle of a function, but not the whole thing... – david van brink Apr 11 '16 at 17:04
• Won't your tile_x == tile_x2 check break anyways if height > 32? But yes, please add more information as mentioned above. – Tyyppi_77 Apr 11 '16 at 18:23

I think you need some documentation about collisions. It seems you want to check the collision between 2 hitbox on a 2D game:

if (rect1.x < rect2.x + rect2.width &&
rect1.x + rect1.width > rect2.x &&
rect1.y < rect2.y + rect2.height &&
rect1.height + rect1.y > rect2.y) {
// collision detected!
}


But you're trying to make a pixel perfect collision, which is needed only when you have check a collision with this code.