How to use waypoints to move an NPC around

I have an NPC in my game and I was wondering how I can use raycasting and waypoints to make it so that it goes around objects and not straight into them. I have a little script for random movement but it has a tendency to run into walls.

Script:

while true do
	local randomlocation = npc.PrimaryPart.Position + Vector3.new(math.random(-50,50), 0, math.random(-50,50))
		
	npc.Humanoid:MoveTo(randomlocation)
	npc.Humanoid.MoveToFinished:Wait()
end

How can I make it so that it is a smart system and not just randomly moving?

2 Likes

You can use PathfindingService to achieve that. PathfindingService use smart system to create a path using waypoints from the starting point to the ending point for your npc. It’s useful as it will:

  1. tell you if it successfully created the path (if it doesn’t, something might be blocking the way between the npc and the destination point)
  2. make ur npc walk around parts using the service.

You can also combine your script with this service to make your npc move smartly to random destinations, using its main function Path:ComputeAsync(startingpoint, randomdestination)
You can get the waypoints using Path:GetWaypoints and loop through them for the npc to walk to each waypoint using :MoveTo()
These functions above are only available to the Path instance.
To create a Path, you can use PathfindingService:CreatePath.
That’s right, basically, PathfindingService is used to just create a Path instance for you to use, since you can’t create Path objects using Instance.new()
(but you can also provide some arguments to CreatePath to create path with certain properties)
Learn how to use pathfinding here.

2 Likes

How would I use these things to make it move to a random point Vector3.new(math.random(1,10), math.random(1,10), 0)

Can you provide a small example of something that would fit my situation?

If you, want it to be smart then,
Do thes script,
–NOTE dele’t you script, Because the script, also have, Smart, Walk

local PathfindingService = game:GetService("PathfindingService")

local Humanoid = script.Parent.Humanoid
local Root = script.Parent:FindFirstChild("HumanoidRootPart")
local goal = game.Workspace.Goal.Position--Change the name of the goal to your Part, that you wann it to come!
local path = PathfindingService:CreatePath()
path:ComputeAsync(Root.Position, goal)
local waypoints = path:GetWaypoints()

wait(2)
for i, waypoint in ipairs(waypoints) do
	Humanoid:MoveTo(waypoint.Position)

	if waypoint.Action == Enum.PathWaypointAction.Jump then
		Humanoid.Jump = true
	end

	Humanoid.MoveToFinished:Wait()
	end```
2 Likes

Path:ComputeAsync(startingpoint, destination)

Each time you run this function, your destination will be the Vector3 of where your NPC will go to. That means, you set the destination to your random Vector3 each time you want the NPC to move randomly.