开发者

Best way to remove sprites from an NSMutable array based on proximity to another sprite?

I have an NSMutableArray of Sprites and I want to remove a few of them based on their proximity to another sprite. So say I have 10 sprites and I want to remove the first 3 that are closest to another sprite.

I can开发者_高级运维't think of a sophisticated efficient way of doing this, anything i've come up with so far seems overly convoluted and inefficient. Any ideas?


Assuming no special data structures or order, you can iterate through each element of your NSMutableArray, keeping track of the indices and distances of the 3 closest sprites in a second NSMutableArray, ordered by increasing distance. Whenever you find a sprite closer than the third element of your temporary array, you drop the third element and insert the index and distance of this new sprite in the array. It's a little tricky, but should be fairly efficient.

If you want to get fancy, you can use a more complex data structure to bucket sprites together based on their location. For 10 sprites that seems like it would be a lot more bother than it's worth.


If you can, you can also keep keep that array of sprites sorted based on the distance. This would not work in a game where things are constantly moving around on the screen of course, but it might work in other situations. Then you can simply take the first three items of the array. (Assuming that they are sorted by distance, longest distance first)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜