Search Unity

Firing at multiple closest targets within a range

Discussion in 'Editor & General Support' started by directusgames, Jul 20, 2015.

  1. directusgames

    directusgames

    Joined:
    May 8, 2015
    Posts:
    14
    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:
    findenemies.png

    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?
     
  2. ColossalPaul

    ColossalPaul

    Unity Technologies

    Joined:
    May 1, 2013
    Posts:
    174
    Not sure if it is faster (need to profile or ask Melvyn). You could use a circle collider (with no visible mesh) and mark it as a trigger. Shoot at those who enters it!
     
  3. directusgames

    directusgames

    Joined:
    May 8, 2015
    Posts:
    14
    Thanks Paul, as I don't want to shoot at all targets within the collider, I think the issue is more finding a quick way to determine which of the enemies inside the range circle are closest
     
  4. Arcatus

    Arcatus

    Joined:
    May 27, 2015
    Posts:
    45
    Perhaps post parts of your code, this shouldn't cause perfomance issues.