So it would takes place on a 2d top down battlefield : a bunch of units (gameObjects) , facing each others (let’s say 50 against 50). Knowing that units will be killed and destroyed, so they will have occasionnally look for new targets.
What would be the best way for one gameObject to know which enemy gameObject is the closest to attack ?
I imagine keeping track of each unit position in 2 lists. List populated the moment I instantiate objects and updated every x seconds. And when needed, iterate through the list ton find the closest one comparing postions.
Or something collider related ? but I have difficulties imagining how it would work ? 1St unit to enter a large size collider would be set as target ?
Or scanning the battlefield each time to know which unit with the tag is the closest ?
I’d go for the 1st solution, but I felt like asking more competent people. Thanks in advance for your insights.
In the end the decision comes down to what you can afford so unless you’re willing to do 50 x 50 distance comparisons, then you’ll either need to utilise any existing physics or add these things to a Spatial Acceleration Structure such as a regular grid or bounding volume hierarchy and query that. Using those you can quickly and easily query what you need.
If you want to go “brute” force then you should, in the very least, do the work on a parallel job comparing all these float2 positions you’ve read from the Transforms. If you were to make it so you only compare against things that were at least within a certain distance/region then that would be even faster but again, you’d need a grid/bvh to do that.
Albeit for a different reason, a really cool presentation of using a regular grid to make things quicker to query can be found here:
very nice concept explained above. I had to give it a go myself. Mine not very good, but the core principals from the video are there.
But I suspect the OP was after something simpler.
50 units on 50 is not a lot of units, but say a few hundred units could get difficult.
With things like colliders, you can actually limit how much the collision can occur by deactivating the collider. Likewise how often to raycast every so and so frame, which in terms of simple collision detection just carefully managing how often and when you spend collision detection resources will go a long way.
In the case of a high number of units, you need some sort of spatial partitioning (like a quad tree), where you divide your scene into 4 parts, and each part also into 4 etc… here is a good visualization of the concept:
If you’re going to do it so they can easily kill anything within range you might as well track their positions……I’d this supposed to be a novice easy level?