I’m trying to do collision check on my game objects. I have a multimap, which contains objects of the same type in each key. The key represents the object’s type . However, all the types derive from the same class. I needed to separate them so the objects know what to do when an object of one type touch another object of other type. But it seems that my way of checking collision is very slow because I noticed that the more objects I add, the slower they move. Can anyone help me? 🙁
Here’s the exact code:
void CheckCollisions()
{
if (!Actors.empty())
{
std::multimap<std::string, boost::shared_ptr<std::vector<PActor>>>::const_iterator it;
it = Actors.begin();
while (it != Actors.end())
{
for (int i = 0; i < static_cast<int>(it->second->size()); i++)
{
std::multimap<std::string, boost::shared_ptr<std::vector<PActor>>>::const_iterator it2;
it2 = Actors.begin();
while(it2 != Actors.end())
{
for (int j = 0; j < static_cast<int>(it2->second->size()); j++)
{
if (i != j)
{
if (Touch(it->second->at(i), it2->second->at(j)))
{
it->second->at(i)->Touch(it2->first, it2->second->at(j));
it2->second->at(j)->Touch(it->first, it->second->at(i));
}
}
}
it2++;
}
}
it++;
}
}
}
Note:
PActor is just a shared_ptr of Actor;
Collision detection is all about minimizing the number of checks you have to do. For example, you should not check each actor against the rest, unless you have very few actors. This is an O(N^2) algorithm that doesn’t scale very well as you add actors (double the number takes four times as long). Perhaps you know the size of each actor? Then you can try collision with actors that are within this range. There’s a library called ANN that can be used to find the nearest neighbours very quickly.
Good luck!