I’m creating a tower defense game, and I used a tutorial for targeting modes, and it works. One problem with it though. On the “First” targeting mode, the function sometimes doesn’t print the best target to attack first, it’ll instead attack an enemy behind it or even two behind it. Is there a good way to make this script “re-check” what would be the best target?
Tutorial I used:
function tower.FindTarget(newTower, range, mode)
local map = workspace.Map:FindFirstChildOfClass("Folder")
local bestTarget = nil
local bestWaypoint = nil
local bestDistance = nil
local bestHealth = nil
for i, mob in ipairs(map.Mob:GetChildren()) do
if mob then
if attackable == true then
if mob.Humanoid and mob.Humanoid.Health >= 0 then
local distanceToMob = (mob.HumanoidRootPart.Position - newTower.HumanoidRootPart.Position).Magnitude
local distanceToWaypoint = (mob.HumanoidRootPart.Position - map.Waypoints[mob.MovingTo.Value].Position).Magnitude
if distanceToMob <= range then
if mode == "Close" then
range = distanceToMob
bestTarget = mob
elseif mode == "First" then
if not bestWaypoint or mob.MovingTo.Value >= bestWaypoint then
bestWaypoint = mob.MovingTo.Value
if not bestDistance or distanceToWaypoint < bestDistance then
bestDistance = distanceToWaypoint
bestTarget = mob
end
end
elseif mode == "Last" then
if not bestWaypoint or mob.MovingTo.Value <= bestWaypoint then
bestWaypoint = mob.MovingTo.Value
if not bestDistance or distanceToWaypoint > bestDistance then
bestDistance = distanceToWaypoint
bestTarget = mob
end
end
elseif mode == "Strong" then
if not bestHealth or mob.Humanoid.Health > bestHealth then
bestHealth = mob.Humanoid.Health
bestTarget = mob
end
elseif mode == "Weak" then
if not bestHealth or mob.Humanoid.Health < bestHealth then
bestHealth = mob.Humanoid.Health
bestTarget = mob
end
end
end
end
end
end
end
return bestTarget
end