Basically, I want to make an NPC that wanders around until he sees a player, then he follows him until the player is dead, and the NPC stops moving if the player is looking at him, however, I have no idea how to do that, so far, I got this script that I found from a tutorial, it works, however, it goes directly to the player. (It’s located on StarterPlayer.StarterCharacterScripts)
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local PathfindingService = game:GetService("PathfindingService")
local ServerStorage = game:GetService("ServerStorage")
local NPC = ServerStorage.NPC
local NPCHumanoid = NPC.Humanoid
local NPCHumanoidRoot= NPC.HumanoidRootPart
local Player = script.Parent
local PlayerHumanoidRoot = Player.HumanoidRootPart
local TeleportingDebounce = false
NPC.Parent = workspace
NPC.PrimaryPart:SetNetworkOwner(nil)
local function FollowPlayer()
local Path = PathfindingService:CreatePath()
local MovingToPosition = PlayerHumanoidRoot.Position - Vector3.new(0, 0, 0)
local ComputedPath = Path:ComputeAsync(NPCHumanoidRoot.Position, MovingToPosition)
return Path
end
RunService.Stepped:Connect(function()
FollowPlayer()
local Path = FollowPlayer()
for _, waypoint in pairs(Path:GetWaypoints()) do
NPCHumanoid:MoveTo(waypoint.Position)
end
end)
Loop through all players, find a player’s character which is closest in the 3D environment (worldspace) to the NPC and then move the NPC’s model towards them.
That doesn’t solve the problem, I think I didn’t explain very well, basically, I want the NPC to have a radius and if a player is in that radius, he’s going to get followed by the NPC
RunService.Stepped:Connect(function()
if (NPCHumanoidRoot.Position - PlayerHumanoidRoot.Position).Magnitude < 5 then
print("Player near NPC.")
FollowPlayer()
local Path = FollowPlayer()
for _, waypoint in pairs(Path:GetWaypoints()) do
NPCHumanoid:MoveTo(waypoint.Position)
end
else
print("The player is far from the NPC.")
end
end)
local function FollowPlayer()
local Path = PathfindingService:CreatePath()
local MovingToPosition = PlayerHumanoidRoot.Position - Vector3.new(math.random(-10,10), 0, math.random(-10,10))
local ComputedPath = Path:ComputeAsync(NPCHumanoidRoot.Position, MovingToPosition)
return Path
end
This should work.
You can remove the -10 or 10 and put in your own, just experiment with them until you get what you want.