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

Stopping NPC with magnitude?

This script makes an NPC follow the player whenever they're close enough, however I've found that when the NPC is close to the player it continues to push it which becomes very annoying

I want to make the NPC stop when it get close to it's target and continue to follow it when the distance between them increases.

Please help.

repeat wait() until script.Parent

local larm = script.Parent:FindFirstChild("Left Arm")
local rarm = script.Parent:FindFirstChild("Right Arm")

function findNearestTorso(pos)
    local list = game.Workspace:children()
    local torso = nil
    local dist = 20
    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("Torso")
            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

while true do
    wait(0.1)
    local target = findNearestTorso(script.Parent.Torso.Position)
    if target ~= nil then
        script.Parent.Humanoid:MoveTo(target.Position, target)
    end
end

1 comment

0

just make an else if condition using magnitude...

1 answer

✓ Accepted answer

Just check the magnitude of the target

while true do
    wait(0.1)
    local target = findNearestTorso(script.Parent.Torso.Position)
    if target ~= nil and (target.Position - script.Parent.Torso.Position).magnitude > 10 then
        script.Parent.Humanoid:MoveTo(target.Position, target)
    end
end

That'll make it only do it if the torso is further than 10 studs away. Mind that this will stop the NPC if your closest Torso is less than 10 studs away.

2 comments

0

Didnt work ;-;

0

Nvm I solved it with a little editing.

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