An enemy detect system for a tower defense game

So, I’m currently working on a tower defense game and I can’t think of an efficient way to make a tower target an enemy.

Let me explain. I want the tower to target the enemy that is the closest to the end and is within the tower’s range. I only know how to make it target the closest enemy, sadly

2 Likes
local MaxDistance = math.huge --Every enemy is checked against this value
local Target --The target chosen for the tower to attack

for _, Enemy in pairs(Enemies) do --Loop through enemies
    --Calculate enemy's distance to end
    local DistanceFromEnd = (Enemy.Position - End.Position).Magnitude
    --Calculate enemy's distance from tower
    local DistanceFromTower = (Enemy.Position - Tower.Position).Magnitude
    
    --Check if enemy is in tower range and it's the closest to the end found so far
    if DistanceFromTower <= TowerRange and DistanceFromEnd < MaxDistance then
        Target = Enemy
        MaxDistance = DistanceFromEnd
    end
end
2 Likes

The problem is, the distancefromend can be inaccurate if the pathway isn’t straight.

To avoid complicated solutions, you could store an os.clock() value inside each npc(in script or in explorer) when they spawn and make the script if statement be if DistanceFromTower <= TowerRange and os.clock()-spawn_os_clock > biggest then where biggest defaults to 0 and gets updated on each loop iteration if the condition is met.

PS: This may cause another issue where npcs with faster speed give false results(you may have to make maths related to their WalkSpeed to counter it)

This logic basically relies to the fact that, if an npc walks for the most amount of time, it has travelled the biggest amount of distance. Assuming all the npcs have the same speed and it remains constant.

4 Likes

Just set the enemy objects up in an array therefore using ipairs to iterate through the enemy positions chronologically which will prevent that error. You’d only have to compare how close it is to the tower.

2 Likes