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

How do you make a NPC attack a person only when that npc is attacked?

Asked by 6 years ago

So lets pretend you have a NPC. If a player hits this NPC and lowers its health, then the NPC starts attacking and following that player. I need someone to create a script which does what I said above. It would be much appreciated.

So I need a NPC which attacks when his health is below 100 and stops when his health is back up to 100.

Either put it down below with instructions of what to do or make a model or provide a link to something.

Once again, I appreciate anyone who is willing to help.

Thanks.

0
I stopped reading at "I need someone to create a script". Make your own. We aren't here to write scripts for you from scratch. T0XN 276 — 6y
0
Ok sorry guys its my first time and next time i will be more considerate thedragonstriker25 -2 — 6y

1 answer

Log in to vote
0
Answered by
zyrun 168
6 years ago
Edited 6 years ago

This should work, but I haven't tested it at all. Next time don't just ask for a script though. :)

local NPC = game.Workspace.NPC -- The NPC's model, make sure to set it corretly.
lcoal Deb = fasle

function findNearestTorso(pos) -- This finds and returns the attacker (the neasrest torso)
    local list = game.Workspace:GetChildren()
    local torso = nil
    local dist = 100 -- Max distance to search for the person, can be low since the attacker should be relatively close(Ranged weapons are a another story)
    local temp = nil
    local human = nil
    local temp2 = nil
    for x = 1, #list do
        temp2 = list[x]
        if (temp2.className == "Model") and (temp2 ~= script.Parent) then
            temp = temp2:findFirstChild("HumanoidRootPart")
            human = temp2:findFirstChild("Humanoid")
            if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
                if (temp.Position - pos).magnitude < dist then
                    torso = temp
                    dist = (temp.Position - pos).magnitude
                end
            end
        end
    end
    return torso
end

function HealthChangedEvent()
    if Deb = true then -- Just so that the function doesn't activate every time the health changes, only when it is lower than 100
        return nil
    end
    while NPC.Humanoid.Health < 100 do
        Deb = true
        wait(1)
        local target = findNearestTorso(script.Parent.HumanoidRootPart.Position)
        if target ~= nil then
            NPC.Humanoid:MoveTo(target.Position, target) -- This actually makes the NPC move
        end
    end
    Deb = false
end

NPC.Humanoid.HealthChanged:connect(function(health)
    HealthChangedEvent() -- Every time the NPC's health changes, the follow function is called
end)
0
Thanks, sorry for not giving a script for you to change, I had the floor and attack i just needed how to do the atack on attack part thedragonstriker25 -2 — 6y
Ad

Answer this question