Having trouble on the way to create a colition detector. I am creating a 2d tile map game that runs on sfml. Currently my player can walk through anything. I already have the block creation function with a parameter for this sort of thing. I just don't know how to apply it.
struct block
{
std::string name[BLOCK_NUMBER+1];
int physics[BLOCK_NUMBER+1]; // The variable used for the colition detector
std::string image[BLOCK_NUMBER+1];
int number;
}block;
Do your blocks move or are they static? Regardless, there is a better way of organising your blocks. Rather than what you have there, rather have a struct for each block and use a vector.
Anyway, here is an example of what I'm talking about, and how you would go about doing collision detection.
struct BoundingBox {
int w; // width
int h; // height
int x; // x position of top-left corner
int y; // y position of top-left corner
};
struct Block {
std::string name; // name of the block
std::string image; // image for the block
BoundingBox bb; // the bounding box of the block
};
std::vector<Block> blocklist;
void create_block(std::string name, std::string image, BoundingBox bb) {
Block b;
b.name = name;
b.image = image;
b.bb = bb;
blocklist.push_back(b);
}
bool testForCollision(const BoundingBox& a, const BoundingBox& b) {
if (a.y + a.h < b.y) returnfalse; // top of a is below bottom of b
if (a.y > b.y + b.h) returnfalse; // bottom of a is above top of b
if (a.x + a.w < b.x) returnfalse; // right of a is more right than left of b
if (a.x > b.x + b.w) returnfalse; // left of a is more left than right of b
returntrue; // otherwise, they must be colliding somewhere
}
Basically, in your update loop, you can just compare the bounding box of the player with every block's bounding box (or just the ones nearby, if you can work out how to do that efficiently).