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

How to do i prevent my NPC from shooting multiple targets at once?

Asked by 2 years ago

Im making a star wars game and my battle droid is supposed to fire its blaster at the closest target it can find, however if there are multiple targets in its range it will fire at all of them at once. How can i prevent this from happening. I understand why its happening but how can i prevent it?

Here is a video link to show whats i mean: https://screencast-o-matic.com/watch/c3V6VQVoT5t

Here is the code that makes it fire:

local agroDist = 50
local parentTorso = script.Parent.Parent.Parent:WaitForChild("Torso")
local origin = script.Parent
local gun = script.Parent.Parent
local selfHuamn = script.Parent.Parent.Parent.Humanoid
local humanTable = {}
local torsoTable = {}

while wait(2) do 
    local target = nil
    for i,v in pairs(game.Workspace:GetChildren()) do
        local human = v:FindFirstChild("Humanoid")
        local torso = v:FindFirstChild("Torso")
        if human and torso and torso ~= parentTorso and (parentTorso.Position - torso.Position).magnitude <= agroDist then
            print("player found near by")
            target = torso
            if target == torso and human.Health > 0 and selfHuamn.Health > 0 then 
                --first step is to make the origin part turn in the direction of the player
                origin.CFrame = CFrame.new(origin.Position, torso.Position)
                local laser = Instance.new("Part", parentTorso)
                laser.Size = Vector3.new(.2,.2,6)
                laser.Anchored = false
                laser.CanCollide = false
                laser.BrickColor = BrickColor.new("Really blue")
                laser.Material = "Neon"
                laser.CFrame = origin.CFrame * CFrame.new(0,0,0)

                local bodyV = Instance.new("BodyVelocity", laser)
                bodyV.MaxForce = Vector3.new(math.huge, math.huge, math.huge)
                bodyV.Velocity = origin.CFrame.LookVector * 150

                laser.Touched:Connect(function(hit)
                    local human = hit.Parent:FindFirstChild("Humanoid")
                    if human then 
                        human.Health = human.Health - 5
                    end
                end)
            end
        end
    end
end
0
try making a variable for the target's name, then having check that variable before every fire. super00rocket 27 — 2y

Answer this question