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

Humanoid:MoveTo(), function not working after is called a second time?

Asked by 3 years ago

This is a ServerScript inside of my NPC

local PathFindService = game:GetService("PathfindingService")

local Path = PathFindService:CreatePath()
local LTH = script.Parent
local Humanoid = LTH.Humanoid
local Destination = game.Workspace.PartAfterSides

local WayPoints
local CurrentWayPointIndex

local function ShowWayPoint()
    local part = Instance.new("Part")
    part.Shape = "Ball"
    part.Material = "Neon"
    part.Size = Vector3.new(0.6, 0.6, 0.6)
    part.Position = WayPoints[CurrentWayPointIndex].Position
    part.Anchored = true
    part.CanCollide = false
    part.Parent = game.Workspace
end

local function FollowPath(Destination)
    Path:ComputeAsync(LTH['Torso'].Position, Destination.Position)
    WayPoints = {}
    if Path.Status == Enum.PathStatus.Success then
        WayPoints = Path:GetWaypoints()
        CurrentWayPointIndex = 1
        ShowWayPoint()
        Humanoid:MoveTo(WayPoints[CurrentWayPointIndex].Position)
    else
        Humanoid:MoveTo(LTH.HumanoidRootPart.Position)
    end
end

local function onWaypointReached(reached)
    if reached and CurrentWayPointIndex < #WayPoints then
        CurrentWayPointIndex = CurrentWayPointIndex + 1
        ShowWayPoint()
        Humanoid:MoveTo(WayPoints[CurrentWayPointIndex].Position)
    end
end

local function OnPathBlocked(BlockedWaypointIndex)
    if BlockedWaypointIndex > CurrentWayPointIndex then
        FollowPath(Destination)
    end
end

-- Connect 'Blocked' event to the 'onPathBlocked' function
Path.Blocked:Connect(OnPathBlocked)

-- Connect 'MoveToFinished' event to the 'onWaypointReached' function
Humanoid.MoveToFinished:Connect(onWaypointReached)

FollowPath(Destination)

The first time when MoveTo is called in FollowPath, MoveToFinished is successful and CurrentWayPointIndex becomes 2, however when MoveTo is run inside OnWaypointReached, the variable reached would be false so the NPC would stop following the path.

If you have questions ask them in the comments. Thanks for reading!

Answer this question