About a year ago I released this demo of grid based proximity management, which was loosely based on some work I had done in Flash 5 (at that time I was calling it zone interaction). Briefly, it allows you to determine which sprites on a 2d plane are near to one another. It is very efficient, and can deal with literally hundreds of sprites (the main limitation is usually the sprites motion and graphics, not the proximity management). For instance, with 350 sprites grid based proximity uses about 700 operations whereas normal iterative proximity testing would use about 61000 operations. For a description of the concept, see my original post on the subject.
When I made the original post, I said I would “be releasing the ProximityManager class in the next few weeks, once I have a chance to play with it further.” Well, I played with it a lot, have used it commercially a few times, and mentioned it in a number of conferences, and still neglected to release it (I’m a naughty boy). Fast-forward to last week, when:
- We rolled it into 2 more projects.
- I received a bunch of emails asking when I would release it.
- Keith (bit-101) released a few experiments based on the concept.
- Brandon (waxpraxis) released a demo using the concept.
And I finally thought I had procrastinated long enough. I have whipped up a simple demo, and made the full class available for download below.
The ProximityManager class is pretty easy to use. There’s only 4 public methods, and a single public property.
myProxMgr.gridSize – property indicating the granularity of the grid.
myProxMgr.addItem(mc) – adds a movieclip to be tracked by the manager.
myProxMgr.removeItem(mc) – removes a movieclip from the manager.
myProxMgr.getNeighbours(mc) – returns an array of movieclips that are neighbours of the specified clip.
myProxMgr.refresh() – recalculates the grid registration of all of the tracked movieclips.
You can download the demo and AS2 class by clicking here.
If you use the ProximityManager, or have ideas on how to improve/optimize it, let me know in the comments. This class could be extremely useful to the whole community, so it would be great to see it continue to improve.
UPDATE: An optimized AS3 version of the source code is now available here.