Issue with my tower defense targeting system

I’m trying to make a perfect targeting system like what Anime Adventures/ASTD currently have…

Currently I’m having issues with the system targeting the incorrect enemies (not the one who’s in first/last place)

I have searched literally everywhere and nothing has solved this issue, creating this topic came as a last resort.

The script is from GnomeCode on his tower defense tutorial since I couldn’t think of a better alternative.

TargetingType[5] is Last Targeting and TargetingType[1] is first targeting.

function TowerFunctions.GetTarget(Tower:Model)
	local Targeting = Tower:WaitForChild("Targeting").Value
	local Upgrade = Tower:FindFirstChild("Upgrade")

	local TowerStats = StatsModule[Tower.Name][Upgrade.Value]
	local Range = TowerStats["Range"]

	local BestTarget = nil
	local BestDist = nil
	local BestWaypoint = nil
	local BestHp = nil
	local WorstHp = nil

	for _, Object in pairs(game.Workspace.Enemies:GetChildren()) do
		local Humanoid = Object:FindFirstChildOfClass("Humanoid")
		if Humanoid and Humanoid.Health > 0 then
			local Dist = (Object:GetPivot().Position - Tower:GetPivot().Position).Magnitude
			local Hp = Humanoid.Health

			if Dist <= Range then
				if Targeting == TargetingTypes[1] then
					local Waypoint = Object["Waypoint"].Value
					local Distance = (Tower.PrimaryPart.Position - workspace.Map:FindFirstChild("Waypoints")[tostring(Waypoint)].Position).Magnitude

					if not BestWaypoint or Waypoint <= BestWaypoint then
						if not BestDist or Distance > BestDist then
							BestWaypoint = Waypoint
							BestDist = Distance
							BestTarget = Object
						end
					end
				elseif Targeting == TargetingTypes[2] then
					if not BestDist or Dist < BestDist then
						BestTarget = Object
						BestDist = Dist
					end
				elseif Targeting == TargetingTypes[3] then
					if not BestHp or Hp > BestHp then
						BestTarget = Object
						BestHp = Hp
					end
				elseif Targeting == TargetingTypes[4] then
					if not WorstHp or Hp < WorstHp then
						BestTarget = Object
						WorstHp = Hp
					end
				elseif Targeting == TargetingTypes[5] then
					local Waypoint = Object["Waypoint"].Value
					local Distance = (Tower.PrimaryPart.Position - workspace.Map:FindFirstChild("Waypoints")[tostring(Waypoint)].Position).Magnitude
					
					if not BestWaypoint or Waypoint >= BestWaypoint then
						if not BestDist or Distance < BestDist then
							BestWaypoint = Waypoint
							BestDist = Distance
							BestTarget = Object
						end
					end
				end
			end
		end
	end
	
	local Pos = nil
	
	if BestTarget then
		Pos = BestTarget.PrimaryPart.Position
	end
	
	return BestTarget, Pos
end
1 Like

I still haven’t found a solution anywhere, I’m very concerned I won’t be able to make it correct in time.

1 Like