The problem is you are applying :MoveTo()
with the wrong parameters as. Your script only runs once as well and doesn’t start the while
loop.
Humanoid:MoveTo(location
, part
)
The first parameter, location
, is a Vector3
value. This is where you want to humanoid to go. The second parameter, part
, is sort of like an offset to the location. If you click the wiki page, you can see a gif that explains it better.
If I were to pass a part
with the location
being Vector3.new(0,0,0)
, the Humanoid will walk to the part’s location and will update when the part’s position changes.
Note: The Humanoid will timeout after 8 seconds of being unable to reach to destination. To avoid this, keep resetting the timeout by running the function again. More info on the wiki page mentioned above.
Making the NPC Better
Now that we understand the :MoveTo()
function, what are some ways we can apply this to our NPC?
PathfindingService
As much as I would like to explain this, I never have used this before. What it does is it creates a path for the NPC to follow based on the geometry of the map. Here is a tutorial on the wiki page:
https://developer.roblox.com/articles/Pathfinding
Chasing the Nearest Player
Using Magnitude
to get the distance between two points in studs will help us determine what player is closest to our NPC and we can apply :MoveTo()
to have the NPC chase them.
01 | local npcHRP = NPC.HumanoidRootPart |
03 | local function GetNearestPlayer(minimumDistance) |
04 | local closestMagnitude = minimumDistance or math.huge |
07 | for i,v in next , game.Players:GetPlayers() do |
08 | local Character = v.Character |
10 | local humanoid = Character.Humanoid |
11 | local HRP = Character.HumanoidRootPart |
12 | if (humanoid.Health > 0 ) then |
13 | local mag = (npcHRP.Position - HRP.Position).Magnitude |
14 | if (mag < = closestMagnitude) then |
16 | closestMagnitude = mag |
Using this function, we get the nearest PlayerObject
. We can ‘convert’ that to a Vector3
and run the :MoveTo()
function with it.
Note: Make sure you apply the loop to keep checking for the nearest player. You also need to keep applying :MoveTo() to keep the NPC from timing out.