I am making a simple flok- or crowd-simulation for a small game.
The behaviour is decent for my needs, but the performance is not.
Basicly I have “alot” of objects(soldiers), which need to spread out while moving to a waypoint.
Ive written a simple version of my code here:
List<Soldier> avoidList = new List<Soldier>();
foreach (Soldier s in gameWorld)
{
if (this == s)
continue;
if (Distance(s, this) <= 5)
{
avoidList.Add(s);
}
}
CalculateNewDirection(avoidList);
So basicly, each soldier checks the distance of every other soldier in the scene, and calculates a direction based on the soldiers which are too close.
Right now im running through x^2 objects.
So if I have 100 objects, i run through 100^2 = 10.000 objects, just to update each individual objects avoidList.
And if i crank it up to 500 objects, i run through 250.000 objects.
Theres gotta be a different and smarter way to do this!
Hope someone can enlighten me 🙂
Off the top of my head, it seems like you are doing an unneccessary square root when calulating the distance. You could check the squared distance instead and check against the squared constant.
Also, there is an improvement to be made where if you find a soldier to avoid, the other soldier will also avoid the first. So each pair only needs to be checked once, if you keep track of multiple avoid lists.
This can be done by saving only the pairs that are too close. In pseudocode
Those are the basic optimizations. If you need to go deeper than that you will need to sort the soldiers based on positions. If you keep track of which soldiers that are on each 5 unit square then no soldier that are more than 2 squares away can possibly influence the given soldier.
Sorting the soldiers on the X and Y axis first will also give similar oppotunities, since you know that if the distance to the next guy on one axis is larger than the radius there is no need to check the distance.
That would give you better performance, but it’s dependent on your data and how sparse the soldiers usually are.