How do I make NPCs that randomly walk around on a path?

The title pretty much says it all. I’m trying to make gta-like NPCs that walk around on a path/sidewalk

I made this as an example, I already have the moving NPCs part, I just don’t know how to make them choose between going left/right/straight when they meet a point, etc

4 Likes

This can be done by using the Pathfinding Service.

Here is a good tutorial on youtube:

You can simply add parts around your map where the npcs might walk to. Then you can use math.random() to select a random part. Then, make the NPC walk to that random part’s position using the information above(PathFindingService).

3 Likes

Sort of feels like a heavy hitting solution to me, you could probably use something a little more lightweight in this scenario.

I would keep an adjacency list around that maps points to neighbors.

Then just call Humanoid:MoveTo on one of those neighbors. Use MovetoFinished to fire it again once you’ve reached that point.

Keep track of the point you came from if you don’t want npcs to do 180s all the time.

9 Likes

This seems like the best solution so far, I’ll try it out, thanks!

1 Like

@Hokker3 If where the npcs will walk will just be open space(no walls or obstacles), then move to is fine.

If you’ve got walls or obstacles or somewhere where jumping will be needed, then you should use the pathfindingservice.

3 Likes

Well it is technically open space, but I wanted the NPCs to walk only on path, I forgot to make it clear in the post

2 Likes

You could add invisible walls so the npcs would have to walk on the path. If you wanted to let players walk through them though, you could use Collision groups.

An alternative, which would take a long time, but would be more accurate, would be to place parts every few studs and use :MoveTo() to make the npcs walk to one of your points, using the parts.

1 Like

I got a question, how can I keep count of the previous point if the walk cycle is running in a loop?

2 Likes

Try storing the name of the point in a variable and double checking that the new point isn’t the old point.

2 Likes

I checked out the adjacency list from the solution and didn’t really understand it and I’m attempting to accomplish something similar to what you are trying to here. Did you ever get it working and how did you end up doing it?

I did the exact same thing back in 2015. Here is my free model of it: Paid Pathfinder Sytem - Roblox
(Hopefully it still works?)

Anyways, 6 years later I am working on customizable pathfinder written in Lua. It’ll be able to generate a nav mesh, but you’ll be able to throw in your custom waypoints as well. Feel free to join the community and follow the development. Any input would be appreciated. Polaris-Nav