Introduction to NPC movement

So far we have been creating games with only real players in it, which means no NPC (Non-Player Character) at all.

How do we create an NPC that behaves inside a Roblox game?

We will learn how to create a Rig, and also look at what the PathfindingService is, which can move our NPC from one place to another, even if there are obstacles in between.

Preparation

1. As usual, open a new Baseplate template:

2. Create a Rig (the NPC body) like below:

3. Create a part and name it “goal”:

Part I: Direct movement

We will now look at how to simply move a NPC from one place to another.

1. Rename our “Dummy” to “npcModel”. Create a script under “npcModel”, and name it “moveNpc”:

2. Inside moveNpc, type the following:

  • line 1: look for the Humanoid in npcModel and assign it to “npc”
  • line 3: Remove anchor in HumanoidRootPart so the NPC can move
  • line 5: Move our npc humanoid to the goal’s position (the green part we created)

If we click “Run” now, the NPC should start moving:

Part II: Passing Obstacle

Very nice! Our NPC can finally move itself!

But what happen if there is something in between? Like a wall?

Create a wall in between:

And click run:

Oops…….

We will first calculate the path using “PathfindingService”:

  • line 1: Include the PathfindingService into our script
  • line 4: Get our torso so we can use it to calculate the path in line 8
  • line 5: Get our goal part
  • line 9: Create a path using PathfindingService
  • line 10: Calculate the path in shortest distance (In this case, from torso position to goal position)

Then, to visualize the path, we need the following:

  • line 13: from the path we calculated, create points along the path.
  • line 14: create a new folder under game.Workspace, to store all the waypoint marks
  • line 16-26: Visualize each waypoint marks into visible small yellow dots

And if we click “Run” now, a visual path will be shown:

Now, type the following to move along the calculated path:

  • line 30: Move to the next waypoint in the current loop
  • line 31: Pause until the next waypoint is reached

Part III: Passing obstacles and jumping over gaps

Let’s create something even harder for our NPC!

Using your current environment and files, create the following:

What happen if we click “Run” now?

You can see that it calculates the correct path, but the NPC cannot actually reach the goal.

It got stuck in the middle since it doesn’t know how to jump!

So, from line 28, change to the following:

  • line 30: If the computer decided the NPC should jump, then
  • line 32: Change our NPC state from Walking to Jumping

Now let’s try again: