I'll show you what I mean, keeping it as basic as possible. Note, I'm not using separate bounding boxes or vectors or anything. Nor am I being clever with access levels, hence the struct.
The assumptions here are that a collision box builds up and right of the position. This isn't great because it's more likely to expand from the centre of the object position but it keeps the math a little simpler. You could easily change it.
Anyway, here goes for simplicity. Hopefully it'll make some sense:
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
#include <iostream>
#include <vector>
struct CollidableObject
{
int x, y;
int width, height;
virtual ~CollidableObject(){};
void setPosition( int x, int y )
{
this->x = x;
this->y = y;
}
void setBoxSize( int w, int h )
{
width = w;
height = h;
}
};
class Player : public CollidableObject {};
class Enemy : public CollidableObject {};
bool checkForCollision( const CollidableObject *a, const CollidableObject *b )
{
if( a->x + a->width < b->x || a->x > b->x + b->width ||
a->y + a->height < b->y || a->y > b->y + b->height )
{
return false;
}
return true;
}
int main( int argc, const char* argv[] )
{
Player* player = new Player();
player->setPosition( 10, 10 );
player->setBoxSize( 5, 5 );
Enemy *enemy = new Enemy();
enemy->setPosition( 11, 11 );
enemy->setBoxSize( 5, 5 );
std::cout << ( checkForCollision( player, enemy ) ? "Objects are colliding" : "Objects aren't colliding" );
delete player;
delete enemy;
return 0;
}
|
Since we've used inheritance here, we can pass the player and enemy into the collision function easily. No casting needed.
You could store all of your collidable objects using this method in a vector and loop through to check for collisions. Ideally, you'd want something more efficient, like a kd-tree, though. That's a different story. :-)
If you did want to keep a vector of collidable objects then that's possible:
1 2 3
|
std::vector<CollidableObject*> collidables;
collidables.push_back( new Player() );
collidables.push_back( new Enemy() );
|