I'd give all collidable objects a rectangle data member to provide a boundary for it.
Suppose we have a box class with a
Rect rect;// declare a suitable type if it doesn't exist
data member.
Let box objects also have a function member hit() for collision testing against other boxes.
Box objects shall be visible, hence they will have a draw()
Box objects shall move, hence they will have a move()
Box objects can collide with each other, hence they have a hit().
These functions would be called each frame, with draw() being called at a possibly different render rate.
The hit() is simple for rectangular areas:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
bool box::hit( box& B )
{
if( Right < B.Left ) return false;// this is left of B
if( Left > B.Right ) return false;// this is right of B
if( Bottom < B.Top ) return false;// this is above B
if( Top > B.Bottom ) return false;// this is below B
// if we made it here then it's a hit
this->onHit( B );// a little polymorphism here permits different box
B.onHit( *this );// types to affect each other differently.
return true;
}
|
Where onHit() would be another (virtual) member function of the box class (heirarchy).
We want to collision test each box against each other one once.
If we have:
vector<box*> pBoxes;// populated with pointers to our colliding boxes
The we would collision test like so each frame:
1 2 3 4
|
for( int a = 0; a < pBoxes.size()-1; ++a )
for( int b = a+1; b < pBoxes.size(); ++b )
pBoxes[a]->hit( *pBoxes[b] );
|