A few years ago, I released an AS2 version of ProximityManager class, which allows you to efficiently track the proximity of large numbers of sprites. You can read a full description of the approach and uses here.

In the last month a couple of people have left comments indicating that they were having difficulty porting it to AS3. This prompted me to port it and do some significant optimizations. The new class runs a lot faster than the original, and is worth taking a quick look at in comparison with the AS2 version even if you don't use it in a project.

Optimizations:

  1. removed two-dimensional arrays (which are very inefficient, especially in AS3) in favor of using a single array using an aggregate x/y index. The aggregate index is assembled with bit operators to make it even more efficient.
  2. added a simple caching mechanism, so that subsequent calls to getNeighbor for the same grid position do not need to recalculate the results
  3. used a Dictionary instance to hold managed items, which makes it much more efficient to remove objects on the fly.
  4. took full advantage of types and casting
  5. other minor tweaks
Note that these optimizations impose a limit of +/- 1024 rows and columns on the ProximityManager. This shouldn't be an issue though: even with a gridSize of only 25 pixels, you would still have an area of 51200 pixels wide and high to work with.

I thought I would recreate the same demo as in my original post to see how it performed. It has five times as many sprites (600 vs 120), and ten times as many connections (~2800 vs ~280), despite the main bottleneck in this demo being the graphics performance. I benchmarked it without graphics, and it seems handle a couple thousand sprites quite easily.

You can grab the source code for the demo and the ProximityManager class here.