My game engine uses the following broadphase collision detection algorithm:
internal void SweepAndPrune()
{
// First: order all objects from left to right on the x-axis:
IOrderedEnumerable<GameObject> axisList = _gameObjects.OrderBy(x => x.LeftRightMost.X);
// loop through all objects:
for(int i = 0; i < axisList.Count(); i++)
{
// For each object, iterate over all the subsequent objects in the list
// and find out if there are overlaps on the x-axis:
for(int j = i+1; j < axisList.Count(); j++)
{
GameObject a = axisList.ElementAt(i);
GameObject b = axisList.ElementAt(j);
if(b.Left > a.Right)
{
// if their is no overlap, then the rest will not overlap as well.
// might as well stop the inner loop here:
break;
}
// if there is an overlap, add A to B's list
// and B to A's list of potential collisions.
// [every object's list of collision candidates is
// cleared before the next frame]
a._collisionCandidates.Add(b);
b._collisionCandidates.Add(a);
}
}
}
The problem is, this algorithm slows down the performance by a lot if there are > 50 objects on screen. Also, the list of GameObject instances (_gameObjects) needs to get sorted another time per frame because I need to order the objects by their distances from the camera (background objects need to get rendered first because of transparency!).
Is there anything I can do to speed things up?
axisListto list or array, and use.Countor.Lengthinstead ofCount(), then replaceELementAtwith regular indexaxisList[i]. This would give you some performance boost, the rest would be outside the loop scope I guess. \$\endgroup\$