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

More efficient way to detect enemies near turret?

Asked by 7 years ago

Basically, I have a turret. I want to know when an object named 'Enemy' is 3 or less studs away from it. If it is, it casts a ray (Don't worry about that, I know how to raycast). Is there an efficient way to do this? Here's what I've got so far:

while wait() do
    for _,v in pairs(game.Workspace:GetChildren()) do
        if string.lower(v.Name) == "enemy" then
            local distance = (script.Parent.Position-v.Position).magnitude
            if distance <= 3 then
                -- code
            end
        end
    end
end

I would just like to know if there's a more efficient way to do this. This seems like there might be, although this is the only thing I've come up with.

0
You might be able to give the turret a cool down time. So the turret would fire for a specific amount of time and then cool down before firing again. I would make sure that the turret fired long enough to completely kill one target. I would also target the same enemy until cooldown or until that enemy is dead. AZDev 590 — 7y
0
Yes, but I mean let's say I want to have other code inside of that same script. It won't run since that while wait() statement is running. Is there a way to detect when the enemy gets close to the turret without using a while loop? AstrealDev 728 — 7y

1 answer

Log in to vote
0
Answered by 7 years ago

The best way to do this is to use a coroutine.

Info: Beginners Guide to Coroutines, Coroutine manipulation, and Lua Corountine

local Run = coroutine.wrap(function()
    while wait() do
        for _,v in pairs(game.Workspace:GetChildren()) do
            if string.lower(v.Name) == "enemy" then
                local distance = (script.Parent.Position-v.Position).magnitude
                if distance <= 3 then
                    -- code
                end
            end
        end
    end
end)

Run() -- Run will not yield

--More code here

Ad

Answer this question