My npc that follows you is broken

So I dug into what kind of errors I am having and I have no clue what is wrong with my script. What I want to do is to make the npc following you but instead it just sat there. Also it should only follow you. Here is my script so far:

NPCCheck = script.Parent:FindFirstChild("Torso")
if NPCCheck == nil then
	warn("Does not have a torso") 
	script:remove()
else
	print("The AI is ready")
end
local human = script.Parent.Humanoid 
while wait() do
	for _, child in pairs(workspace:GetChildren()) do
		if child:IsA('Model') and child:FindFirstChild('Humanoid') and (script.Parent.Torso.Position - child.Torso.Position).magnitude < 30 and (script.Parent.Torso.Position - child.Torso.Position).magnitude > 0.5 then
			script.Parent.Humanoid.WalkSpeed = 20
			human:MoveTo(child.Torso.Position)
			script.Parent.Torso.Touched:connect(function()
				human.Jump = true
			end)
			if human then
				script.Parent.HealArea.Script.Enabled = true
			end
		end
	end
end

If you already found an error please tell me and Ill try to fix it. Thanks!

1 Like

Make sure the HumanoidRootPart of your NPC is not anchored.

Unless your game only uses R6 Rigs you may want to change Torso to be HumanoidRootPart or PrimaryPart.

Check the Output window for errors.

Try this

local RANGE = 30

local Players = game:GetService("Players")

local npc = script.Parent
local npcHumanoid = npc.Humanoid 

-- Jump when touched
script.Parent.Torso.Touched:Connect(function()
	npcHumanoid.Jump = true
end)

while true do
	local npcPosition = npc:GetPivot().Position
	local nX, nZ = npcPosition.X, npcPosition.Z
	for _, player in Players:GetPlayers() do
		local target = player.Character
		if not target then continue end -- Skip, no character

		local targetPosition = target:GetPivot().Position
		local tX, tZ = targetPosition.X, targetPosition.Z
		if RANGE^2 > (tX - nX) ^ 2 + (tZ - nZ) ^ 2 then
			npcHumanoid:MoveTo(targetPosition)

			script.Parent.HealArea.Script.Enabled = true
			break -- Stop scanning for other players
		end
	end
	task.wait(0.05)
end
1 Like

It worked but when the script called HealArea is activated, it stops moving but I want it to keep moving while it is activated.

There are a few things that could be improved with your code to make it work correctly. Here’s a revised version that should achieve what you’re looking for:

local MAX_FOLLOW_DISTANCE = 30 -- maximum distance for NPC to follow player
local MIN_FOLLOW_DISTANCE = 3 -- minimum distance for NPC to follow player
local FOLLOW_UPDATE_INTERVAL = 0.5 -- interval in seconds for updating NPC follow

local NPCCheck = script.Parent:FindFirstChild("HumanoidRootPart")
if not NPCCheck then
warn("NPC does not have a HumanoidRootPart")
script:Destroy()
return
end

local humanoid = script.Parent:FindFirstChildOfClass("Humanoid")
if not humanoid then
warn("NPC does not have a Humanoid")
script:Destroy()
return
end

local function getClosestPlayer()
local closestPlayer = nil
local closestDistance = math.huge

for _, player in pairs(game.Players:GetPlayers()) do
	if player.Character and player.Character:FindFirstChild("HumanoidRootPart") then
		local distance = (NPCCheck.Position - player.Character.HumanoidRootPart.Position).magnitude
		if distance < closestDistance and distance <= MAX_FOLLOW_DISTANCE and distance >= MIN_FOLLOW_DISTANCE then
			closestPlayer = player
			closestDistance = distance
		end
	end
end

return closestPlayer, closestDistance
end

while true do
local player, distance = getClosestPlayer()
if player then
script.Parent.Humanoid.WalkToPoint = player.Character.HumanoidRootPart.Position
else
script.Parent.Humanoid.WalkToPoint = nil
end


wait(FOLLOW_UPDATE_INTERVAL)
end

Here’s a summary of the changes made:

The script now checks for the presence of a HumanoidRootPart instead of a Torso to make sure the NPC can move properly.
The script now checks for the presence of a Humanoid to make sure the NPC can move properly.
The script now has a function getClosestPlayer() that finds the closest player within the specified range.
The NPC now moves towards the closest player’s HumanoidRootPart using the WalkToPoint property.
The script waits for a specified interval before updating the NPC’s movement again, to avoid excessive updates.
I hope this helps!

1 Like

The script is really cool and I like your idea but when i tested it, the npc just stood still. Have you tried to test it out?

The problem with the code above is that it isn’t using MoveTo, a method of Humanoid.

Luckily, MoveTo has a 2nd argument, which you can provide a part to move to:

Replace this with:

script.Parent.Humanoid:MoveTo(player.Character:GetPivot().Position, player.Character.PrimaryPart or player.Character.HumanoidRootPart)

Replace this with:

script.Parent.Humanoid:Move(Vector3.zero)

And you should be good!

But everything else in that script is probably what you want to achieve.

The npc isnt moving at all but some codes I have created are here. There is something wrong in them that caused the npc to not move.

local db = false
function onTouched(part)
	wait(5)
	local h= part.Parent:findFirstChild("Humanoid")
	if h~=nil and not db then
		db = true		
		script.LaserSound:Play()
		script.HealBotTaunt:Play()
		script.Parent.Transparency = 0
		script.Parent.Parent.HealAura.Material = Enum.Material.Neon
		script.Parent.Size = Vector3.new(1,1,1)
		script.Parent.BlockExpansion.Enabled = true
		script.Parent.Healing.Enabled = true
		wait(5)
		script.Parent.Parent.HealAura.Material = Enum.Material.ForceField
		script.Parent.Transparency = 1
		script.Parent.BlockExpansion.Enabled = false
		script.Parent.Healing.Enabled = false
		script.Parent.Size = Vector3.new(13,13,13)
		task.wait(15)
		db = false
	end

end 

script.Parent.Touched:connect(onTouched)
script.Parent.Size = Vector3.new(1,1,1)
local tweenService = game:GetService("TweenService")

local part = script.Parent

part.Size = Vector3.new(1,1,1)

tweenService:Create(
	part,
	TweenInfo.new(
		2,
		Enum.EasingStyle.Linear,
		Enum.EasingDirection.In,
		0,
		false,
		0
	),
	{Size = Vector3.new(31, 31, 31)} 
):Play()

My npc is unanchored by the way. Also, RickAstll3y’s script was working but it stopped moving when it goes to my location but when I move it, it starts working and stops working and so on.

the human rootpart is unanchored also I used r6 and the humanoid rootpart is the primary part too. sorry for the late message because I was busy testing some other people’s script.

Will anyone help me finish this error? I think I’m close to finishing it but I’m not sure.

I have no clue why this is happening. Can you better describe what the partially working solution’s problem is?

so the problem is the script looks fine but the other 2 I posted has to do with something that stops the movement of an npc. The first script is the script for the model and the second script is in the first script.

I’ve also looked into the output and there was really nothing wrong going on. I have no clue why is the robot stopping itself.

Although Rick’s script actually worked but the problem is the robot stops moving when you get too close. Do you guys think you can probably solve this?

Try this

local RANGE = 30

local Players = game:GetService("Players")

local npc = script.Parent
local npcHumanoid = npc.Humanoid 

-- Jump when touched
script.Parent.Torso.Touched:Connect(function()
	npcHumanoid.Jump = true
end)

while true do
	local npcPosition = npc:GetPivot().Position
	local nX, nZ = npcPosition.X, npcPosition.Z
	for _, player in Players:GetPlayers() do
		local target = player.Character
		if not target then continue end -- Skip, no character

		local targetPosition = target:GetPivot().Position
		local tX, tZ = targetPosition.X, targetPosition.Z
		if RANGE^0 > (tX - nX) ^ 0 + (tZ - nZ) ^ 0 then
			npcHumanoid:MoveTo(targetPosition)

			script.Parent.HealArea.Script.Enabled = true
			break -- Stop scanning for other players
		end
	end
	task.wait(0.05)
end
NPCCheck = script.Parent:FindFirstChild("Torso")
if NPCCheck == nil then
    warn("Does not have a torso") 
    script:remove()
else
    print("The AI is ready")
end

local human = script.Parent.Humanoid 
human.WalkSpeed = 20

while wait(0.5) do
    local closestModel
    local closestDistance = math.huge
    
    for _, child in pairs(workspace:GetChildren()) do
        if child:IsA('Model') and child:FindFirstChild('Humanoid') and child.Humanoid.Health > 0 then
            local distance = (script.Parent.Torso.Position - child.Torso.Position).magnitude
            if distance < closestDistance and distance > 0.5 then
                closestModel = child
                closestDistance = distance
            end
        end
    end
    
    if closestModel then
        if human.WalkToPoint == nil or (human.WalkToPoint - closestModel.Torso.Position).magnitude > 2 then
            human:MoveTo(closestModel.Torso.Position)
        end
    end
end

human.MoveToFinished:Connect(function(reached)
    if reached then
        -- NPC has reached its destination
        script.Parent.Torso.Anchored = true
        wait(1)
        script.Parent.Torso.Anchored = false
    end
end)

The NPC will stop moving for 1 second after reaching its destination before moving again. This can help prevent the NPC from getting stuck in a loop if it keeps moving towards the same model.

It didnt work unfortunately. The npc was not moving at all.

Yours did not work either. But im pretty sure its this script that is causing the problem with the npc’s mobility. This script came from the model I created. Its a clock that rotates itself.

-- >>: Variables
-- >>: Variables
local runService = game:GetService("RunService")

local model = script.Parent

-- >>: Main Code
local function Heartbeat(deltaTime)
	model:PivotTo(model:GetPivot() * CFrame.Angles(math.rad(0), math.rad(1), math.rad(0)))
	
end

runService.Heartbeat:Connect(Heartbeat)

Based on your script, it seems that the NPC is only supposed to follow a player if the player is within a certain distance range. However, there are a few potential issues with the script that could be causing problems:

  1. The NPC is not following the player: One issue could be that the NPC is not able to move towards the player’s position. This could be caused by the line “human:MoveTo(child.Torso.Position)” not executing properly. Try printing out the value of “child.Torso.Position” to see if it’s returning the expected value. Also, make sure that the NPC’s movement is not being obstructed by any objects in the environment.

  2. The NPC is not stopping when the player moves out of range: Another potential issue could be that the NPC is continuing to follow the player even when they move out of range. To fix this, you can add an “else” statement after the “if” statement to set the NPC’s walk speed to 0 and stop it from following the player.

  3. The NPC is following other entities: The script currently checks for any model with a humanoid in the workspace and makes the NPC follow them. If there are other entities in the workspace that meet these conditions, the NPC may be following them instead of the player. To fix this, you can add a check to make sure that the humanoid belongs to the player.

Here’s an updated version of your script that addresses these issues:

local player = game.Players.LocalPlayer
local humanoid = script.Parent.Humanoid

while wait() do
    local closestDist = math.huge
    local closestHumanoid = nil
    
    for _, child in pairs(workspace:GetChildren()) do
        if child:IsA('Model') and child:FindFirstChild('Humanoid') and child.Humanoid ~= humanoid and child.Humanoid.Health > 0 then
            local dist = (script.Parent.Torso.Position - child.Torso.Position).magnitude
            if dist < closestDist and dist < 30 then
                closestDist = dist
                closestHumanoid = child.Humanoid
            end
        end
    end
    
    if closestHumanoid then
        humanoid.WalkSpeed = 20
        humanoid:MoveTo(closestHumanoid.Parent.Torso.Position)
        script.Parent.Torso.Touched:connect(function()
            humanoid.Jump = true
        end)
        if humanoid then
            script.Parent.HealArea.Script.Enabled = true
        end
    else
        humanoid.WalkSpeed = 0
    end
end

In this updated version, the script finds the closest humanoid that is not the NPC itself and not a player, and only follows that entity. It also stops following the entity if it moves out of range. Note that this script assumes that the NPC is a child of the player’s character. If it’s not, you’ll need to modify the script accordingly.

The npc is still not moving, the npc itself is unanchored too and there is probably something wrong with its character. Heres the model.
(3) The Robot - Roblox (Its mine btw)
You might want to put this is the new baseplate and see if there is something wrong.