Colition Detector?!!

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;

void create_block(std::string name, int physics, std::string image) //my functio
{
block.number++;
block.physics[block.number]=physics;
//block_mesh.clear_array(block.number,mesh);
block.name[block.number]=name;
block.image[block.number]=image;
}
Last edited on
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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) return false; // top of a is below bottom of b
    if (a.y > b.y + b.h) return false; // bottom of a is above top of b
    if (a.x + a.w < b.x) return false; // right of a is more right than left of b
    if (a.x > b.x + b.w) return false; // left of a is more left than right of b
    return true; // 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).
Great idea. This will work perfectly.
Topic archived. No new replies allowed.