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

How to stop npc from following path midway?

Asked by 1 year ago

So I have a script, and I copied the pathfind script that follows it's enemy. And if it sees it's enemy it's gonna stop itself from walking to the target.

Well, that's what I want it to do, but it doesn't work.

Script (not full script):

local ray1 = Ray.new(script.Parent.M16.Shoot.Position, (v.HumanoidRootPart.Position - script.Parent.M16.Shoot.Position).Unit * 1000)
            local hit1, position1 = workspace:FindPartOnRayWithIgnoreList(ray1, {script.Parent})
            if not hit1:IsDescendantOf(v) then
                local Destination = v.HumanoidRootPart.Position
                local Path = PathfindingService:CreatePath()
                local NPC = script.Parent
                local Humanoid = NPC.Humanoid
                Path:ComputeAsync(NPC.PrimaryPart.Position, Destination)

                local activeCoroutine = nil
                local follow=true

                -- Loop update
                coroutine.wrap(function()
                    while (follow) do
                        if hit1:IsDescendantOf(v) then follow = false break end
                        wait(1/3)
                        update()
                    end
                end)()


                function update()
                    if script.Parent.Humanoid.Health ~= 0 then
                        Path:ComputeAsync(NPC.PrimaryPart.Position, Destination)
                    end

                    local Waypoints = Path:GetWaypoints()
                    table.remove(Waypoints, 1)  -- First waypoint seems to always be origin

                    coroutine.wrap(followPath)(Waypoints) -- Follow new path
                    if hit1:IsDescendantOf(v) then return end
                end

                function followPath(waypoints)
                    activeCoroutine = coroutine.running()
                    if hit1:IsDescendantOf(v) then return end
                    if hit1:IsDescendantOf(v) then coroutine.close(activeCoroutine) end
                    for _, point in ipairs(waypoints) do
                        if hit1:IsDescendantOf(v) then break end
                        if activeCoroutine~=coroutine.running() then
                            return end  -- No longer active path
                        Humanoid:MoveTo(point.Position)
                        Humanoid.MoveToFinished:Wait()
                        if point.Action==Enum.PathWaypointAction.Jump then
                            Humanoid.Jump = true 
                        end
                    end
                end
            end

Please help

Answer this question