So I am making a RTS and have a ton of units. The way I make them shoot each other is to find the closest unit and shoot it, but only if its in range obviously. If it doesn’t find a unit within range then it tries again in a second. (If they get in range and 1 unit takes a few seconds to find it then its at a disadvantage so its only 1 second before retrying.) The problem is that when there is over 100 units, I am thinking that 100 units constantly looping through 100 units would get laggy or use up a lot of power. (I want to get to 200+ units.)
My findClosestUnit() function basically just loops through all enemey units and finds the closest one. Is there a better way? I don’t think so but I sware anytime I post something my RTS gets improved a ton.
function Distance(e, h) --e is position1, h is position2
return math.sqrt(((e.X - h.X)*(e.X - h.X))+((e.Z - h.Z)*(e.Z - h.Z))) --Does not use the Y, just x-y distance
end
I do not want Y incorporated into this because if a plane is flying high I dont feel like making it become out of range… otherwise i’d use .magnitude
So let’s not think too micro-optimization here and consider the fact that this is an algorithmic problem and not mathematical.
Instead of checking 100 units every second, you should come up with a method in which you know when you do not need to check.
An extreme example, you do a initiation check and find that 34 of the 100 units are reasonably far away that they can skip a few ticks of checking (let’s say 3-6 seconds). So for the next 3-6 seconds, they are not part of the loop but are then added back into the main distance check loop afterwards. You’ve optimized your functionality this way rather than possibly uselessly running all 100 checks. When a looped unit is too far away, remove them from that loop for a few iterations.
Thanks for the help. I will use the enemey units speed and distance along with the range to determine how much wait time until they’re added back into the loop.