Tower Defense "First" Targeting Mode Not Working Efficiently

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
3 Likes

Im currently using this video to make target mode too and i know what’s the problem is.

So we using those waypoints for the mob to move and get those wapoint number to the intvalue MovingTo on the mob. Example: Mob moving to Waypoint 27 and his MovingTo Value is 27.

How i fixed it is just putting more waypoint but its a waste of time. I know out theres a better method to do that but i didnt know so i just do this lol.

Sorry for bad explaining, im not very good at english

Ey comrade. I found the issue of this code. Due to you firing the FindTarget.
Check this post: Help with Tower Defense “First” and "Last" Targeting - #6 by Datte_Reflex1