Gnomecode "First" targeting TD error

So i have followed the gnomecode tower defense series and i have came into an issue, when there are 2 types of zombies so like normal and speedy one. First they start shooting the normal ones but even if the speedy ones go past them and they are first, the towers still shoot the basic ones until there isnt any normal one left then move on to other types?..

function tower.FindTarget(newTower, range, mode)
	local bestTarget = nil
	local bestWaypoint = nil
	local bestDistance = nil
	local basehealth = nil

	for i, mob in ipairs(workspace.Mobs:GetChildren()) do
		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 == "First" then
				if not bestWaypoint or mob.MovingTo.Value > bestWaypoint then
					bestWaypoint = mob.MovingTo.Value
					bestTarget = mob
				end
				-- make the tower target the one that is close to the best waypoint or the best in distance. Target the first zombie on the path

				
				
				
				
				
				if not bestWaypoint or mob.MovingTo.Value >= bestWaypoint then
					if not bestWaypoint or mob.MovingTo.Value > bestWaypoint then
					end
					
					bestWaypoint = mob.MovingTo.Value
					
					if not bestDistance or distanceToWaypoint < bestDistance then
						bestDistance = distanceToWaypoint
						bestTarget = mob
					end
				end
				
				
				
			end
			return bestTarget
			
		end
		bestTarget = nil

	end
end

Pretty sure gnomecode has the TD Place open sourced on his website

Just download the rbxl file and compare your code

https://gnome.codes/tutorials/TowerDefense/

1 Like
function tower.FindTarget(newTower, range, mode)
	local bestTarget = nil
	local bestWaypoint = nil
	local bestDistance = nil
	local basehealth = nil

	for i, mob in ipairs(workspace.Mobs:GetChildren()) do
		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 == "First" then
				if not bestWaypoint or mob.MovingTo.Value >= bestWaypoint then
					if bestWaypoint and mob.MovingTo.Value > bestWaypoint then
						bestDistance = nil
					end
					
					if not bestDistance or distanceToWaypoint < bestDistance then
						bestDistance = distanceToWaypoint
						bestWaypoint = mob.MovingTo.Value
						bestTarget = mob
					end
				end
			end
		end
	end
	
	return bestTarget
end

I trying fixing it from phone so i might typing somewhere wrong

2 Likes

Compared, used his, nothing works, same issue.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.