Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 6 years ago
Edited 6 years ago

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.

0
does it shoot the first enemy in range at least the first time? JakePlays_TV 97 — 6y
0
Sorry, late response. It only does that with one enemy, usually it attacks the first one that appears on the map. OsterDog 14 — 6y
0
does it shoot the first enemy in range at least the first time? JakePlays_TV 97 — 6y

2 answers

Log in to vote
0
Answered by
Tomstah 401 Moderation Voter
6 years ago

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.

Ad
Log in to vote
0
Answered by 6 years ago
Edited 6 years ago
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

Answer this question