I'm working in a 2d environment and have hundreds of objects, brute force collision checking would be out of the question, but would my method below work?
For example, lets say I have a std::vector<GameObj*> objectsVector
to hold all objects and a std::multimap<Point2D, GameObj*> objectsMap
(basically a map which takes a 2d point representing a GameObject's coordinate as a key and the object itself as a value) to get any object associated with a point. If I want to do collision checking for an object, I could use a function that looks like this:
void World::checkForCollisions()
{
for (int i = 0; i < objectsVector; ++i) {
GameObj* currObj = objectsVector[i];
for (
int x = (int)currObj->getX() - (int)currObject->getWidth();
x < currObj->getX() + 2*currObj->getWidth();
x++
)
{
for (
int y = (int)currObj->getY() - (int)currObject->getHeight();
y < currObj->getY() + 2*currObj->getHeight();
y++
)
{
pair<multimap<Point2D, GameObj*>::iterator,multimap<Point2D, GameObj*>> range = objectsMap.equal_range(Point2D(x, y));
for (
multimap<Point2D, GameObj*>::iterator it=range.first;
it!=range.second;
++it
)
{
if (checkCollision(currObj, it->second))
currObj->handleCollision(it->second);
}
}
}
}
}
Is this even remotely efficient? Because it doesn't seem to be. It basically just scrolls through the vector and checks to see if it collides with nearby objects. Problem is, I have to use 2 containers AND when things move, I have to pretty much reinitialize the entire map, because the keys would be invalid! Is there any way to improve this collision-checking function, or should I scrap the whole thing altogether and use spatial hashes or a quad-tree?