How to move a player with Pathfinding and waypoints?

I have a local player script in starter player scripts that are supposed to move the character to a set location or not based off the math.random value or “roll” value.

There’s two errors that occur. "attempt to index nil with ‘MoveToFinished’, Line 47 from
humanoid.MoveToFinished:connect(onWaypointReached)
Also ‘HumanoidRootPart is not a valid member of Player’ Line 21 from path:ComputeAsync()


local player = game:GetService("Players").LocalPlayer
local PathfindingService = game:GetService("PathfindingService")
local humanoid = player.Character  --:WaitForChild("Humanoid")

local CheckPoints = game.Workspace.Checkpoints
local Checks1 = CheckPoints.Checks1
local Checks2 = CheckPoints.Checks2
local Checks3 = CheckPoints.Checks3
local Checks4 = CheckPoints.Checks4
local destinations={Checks1.Check1, Checks1.Check2} -- the list of parts that make up the path to follow
local nextDestination=1
local waypoints
local nextWaypoint

local roll = math.random(0,2)
wait(5)

local function CreatePath()

	local path = PathfindingService:CreatePath()
	path:ComputeAsync(player.HumanoidRootPart.Position, destinations[nextDestination].Position)
	if path.Status == Enum.PathStatus.Success then
		waypoints = path:GetWaypoints()
		--ShowWayPoints(waypoints) -- Delete this line if you don't want to display the waypoints
		nextWaypoint=1
		humanoid:MoveTo(waypoints[nextWaypoint].Position)
	end

end

local function onWaypointReached(reached)

	if reached and nextWaypoint < #waypoints and roll > 0 and nextDestination ~= roll then
		nextWaypoint+=1
		humanoid:MoveTo(waypoints[nextWaypoint].Position)
	else 
		nextDestination+=1
		if nextDestination>#destinations then 
			print("Reached Final Destination.") -- What happens after path is completed
		else 
			CreatePath() --Move to the next part in the list 

		end
	end

end
humanoid.MoveToFinished:Connect(onWaypointReached)
CreatePath()

CreatePath function creates the path/waypoints for the onWaypointReached function to move to. It loops through an array to get the next destination. How many of these destinations will be determined by the amount of the roll.

I think the biggest problem I’m having currently is figuring out how to get the player to move. It’s not the same as getting a humanoid model to move.

2 Likes

There are two main problems that initially jump out. You have defined your humanoid variable as being equal to the Player’s Character, not their humanoid.

It would also be a good idea to wait for the character to spawn in before attempting to access it.

I’d start by changing the first 3 variables at the top of your script to the following

local Players = game:GetService("Players")
local Player = Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:WaitForChild("Humanoid")
2 Likes