Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can you get the first enemy on a track? (FIXED PROBLEM)

I am developing a tower defense style game. When the towers shoot, they shoot at random enemies in range, and it doesn't get the one that's closest to the end. I have tried if functions and it still doesn't get the first one. The code below gets an enemy in range that exists. However, it always shoots the enemy that is the farthest away from the end when in fact I want the opposite.

local closestpart
		for n,e in pairs(workspace.Game.Enemies:GetChildren()) do
			if e ~= nil then
				local mag = (tower.PrimaryPart.Position-e.PrimaryPart.Position).magnitude
				if mag <= script.Parent.Range.Value then
					closestpart = e
				end
			end
		end

I have a source value, which says where it is on the map, but I cant seem to find out how to get that to make the towers ALWAYS shoot the first enemy that is in range.

3 comments

0

does it shoot the first enemy in range at least the first time?

0

Sorry, late response. It only does that with one enemy, usually it attacks the first one that appears on the map.

0

does it shoot the first enemy in range at least the first time?

2 answers

✓ Accepted answer

Well, the best idea to do this is if the tower defense is a constant distance, make a speed value for each "monster" or whatever they are then add another value which counts how long they've existed. Then take the product of time and speed and divide it by the total distance of the track. This is the percentage of how far they're done with the track. After doing so, just compare that percentage.

local closestpart

while true do
	for n,e in pairs(workspace.Game.Enemies:GetChildren()) do 
		if e~= nil then
			local mag = (tower.PrimaryPart.Position-e.PrimaryPart.Position).magnitude
				if mag <= script.Parent.Range.Value then
					closestpart = e
				end
			end
		end
	end

This discussion is preserved as it was. New answers, comments, and votes are closed.