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

Why is this script not moving the NPC toward a player when it gets in its radius of range?

Asked by 4 years ago

Hello! I'm trying to make a npc find when a player is in a radius of 200 and goes towards that player or me. I basically have just a normal script inside of the normal R16 Dummy. That is just named "Dummy". Anythings helps. Here is the script:

function findTarget()
    local dist = 200
    local target = nil
    for i,v in pairs(workspace:GetChildren()) do
        local humanoid = v:FindFirstChild("Humanoid")
        local head = v:FindFirstChild("Head")
        if humanoid and head and v.Name ~= "Dummy" then --Name all the Npc's you don't want getting attacked.
            if (head.Position - rootpart.Position).magnitude < dist and humanoid.Health > 0 then
                dist = (head.Position - rootpart.Position).magnitude
                target = head
            end
        end
    end
    return target
end

 while wait(1) do
    local head = findTarget()

    if head then
        local ray = Ray.new(rootpart.Position, (head.Position - rootpart).Unit * 200)
        local hit,position = workspace:FindPartOnRayWithIgnoreList(ray,  {script.Parent} )
        if hit then
            print(hit.Name)
            if hit.Parent:IsADescendantOf(head.Parent) then
                human:MoveTo(head.Position)
            else
                human:MoveTo(head.Position)
                wait(0.4)
                path = game:GetService("PathfindingService"):FindFirstPathAsync(rootpart.Position,head.Position)
                points = path:GetWaypoints()
                if path.Status == Enum.PathStatus.Success then
                for i,v in pairs (points) do
                    human:MoveTo(v.Position)
                    human.MoveToFinished:wait(2)
                    if v.Action == Enum.PathWaypointAction.Jump then
                        human.Jump = true
                    end
                    if (points[#points].Position - head.Position).magnitude > 15 then
                        break
                    end
                end
                else
                    human:MoveTo(head.Positon)
            end
        end
    end
    end
    end

Also, in the Output its saying: "Workspace.Dummy.Script:24: bad argument #2 to '?' (Vector3 expected, got Object)" and points me to line 24: local ray = Ray.new(rootpart.Position, (head.Position - rootpart).Unit * 200) Maybe that's the issue? I have no idea, thought that would help.

Answer this question