# How to correctly make a "first" targeting system for a Tower Defense game?

Hi, I am working on a tower defense game and I am struggling on how to measure which enemy is first on the track. Right now I am using a Distance, Speed, Time formulae in which I find the distance by multiply the speed by delta time with RunService.Heartbeat then add it to a variable called distanceInTrack. Then the troop will find all the enemies in range then picks the one with the highest distanceInTrack.It sometimes work but still quite inaccurate. Is there a better way to detect the first enemy?

``````local heartbeatFunc
heartbeatFunc = runService.Heartbeat:Connect(function(dt)
if self and self.Model and self.Model:FindFirstChild("Humanoid") and self.Model.Humanoid.Health > 0 then
self.DistanceInTrack += self.Model.HumanoidRootPart.Velocity.Magnitude * dt
else
heartbeatFunc:Disconnect()
heartbeatFunc = nil
end
end)
``````
``````function troop:GetAttackableEnemy(enemyToIgnore)
if not self or not self.Model or not self.Model:FindFirstChild("Humanoid") or self.Model:FindFirstChild("Humanoid").Health <= 0 then return end
local enemiesInRange = {}
for i, enemyModel in pairs(enemyFolders:GetChildren()) do
local magnitude = getMagnitude(self.Model, enemyModel)
if magnitude < self.Range then
if enemyModel == enemyToIgnore then continue end
table.insert(enemiesInRange, enemyModel)
end
end
if #enemiesInRange == 0 then return end
if #enemiesInRange == 1 then
return enemiesInRange[1]
end
if self.Targetting == "First" then
-- Check targetting
local firstEnemy = {-1, nil}
for i, enemy in pairs(enemiesInRange) do
if enemy:GetAttribute("DistanceInTrack") > firstEnemy[1] then
firstEnemy[1] = enemy:GetAttribute("DistanceInTrack")
firstEnemy[2] = enemy
end
end
if firstEnemy[2] ~= nil then
return firstEnemy[2]
end
end
end
``````