Hi guys,
I’m trying to find an efficient way to determine what the closest ‘x’ number of objects is to a point within a range.
I’ll try to illustrate below:
I want the cannon to be able to fire at multiple enemies, but not ALL enemies within range.
For example, i want it to fire at 3 enemies. As there are 7 enemies within range, I would like to find the closest 3 enemies and then fire at them.
The enemies may move out of range or die so I must re-check the closest enemies before the cannon fires each time
I’ve tried several ways of doing this but haven’t come up with anything that’s efficient. As it will need to check which enemies are closest pretty constantly, I end up using up a fair amount of processing just on this.
What I have so far:
I use Physics2D.OverlapCircleAll to find all the targets within a certain range. I then iterate through each and sort by distance from the cannon. Once this complete I just pick the top ‘x’ number to fire at.
I’m designing this for mobile and having that much iteration each time the cannon fires (every second or so) starts to lower the fps pretty quickly (particularly with multiple cannons).
Is there an easier way to do this?