Hi so i tried making a npc follow you and i tested it out but the only problem is that at the start the part follows (also i was testing the system thats why i am using a part) and when you go backwards the part is infront of you instead of behind you?
heres a script:
local click = script.Parent.ClickDetector
click.MouseClick:Connect(function(player)
if player then
local Character = player.Character
local HRP = Character.HumanoidRootPart
while true do
wait(0.01)
script.Parent.CFrame = HRP.CFrame + Vector3.new(4,0,4)
end
end
end)
local npc = script.Parent
local humanoid = npc:FindFirstChild("Humanoid")
local rootPart = npc:FindFirstChild("HumanoidRootPart")
local walkAnimationId = "rbxassetid://913402848" -- walk ID
local walkAnimation = Instance.new("Animation")
walkAnimation.AnimationId = walkAnimationId
local walkAnimTrack = humanoid:LoadAnimation(walkAnimation)
-- distance from the player
local distanceToFollow = 15
local distanceToStop = 5
local function getClosestPlayer()
local closestPlayer = nil
local shortestDistance = distanceToFollow
for _, player in pairs(game.Players:GetPlayers()) do
local character = player.Character
if character and character:FindFirstChild("HumanoidRootPart") then
local playerRootPart = character.HumanoidRootPart
local distance = (rootPart.Position - playerRootPart.Position).Magnitude
if distance < shortestDistance then
closestPlayer = player
shortestDistance = distance
end
end
end
return closestPlayer
end
local function followPlayer()
local player = getClosestPlayer()
if player then
local targetPosition = player.Character.HumanoidRootPart.Position
local distance = (rootPart.Position - targetPosition).Magnitude
if distance > distanceToStop then
humanoid:MoveTo(targetPosition)
if not walkAnimTrack.IsPlaying then
walkAnimTrack:Play()
end
else
humanoid:MoveTo(rootPart.Position)
walkAnimTrack:Stop()
end
else
humanoid:MoveTo(rootPart.Position)
walkAnimTrack:Stop()
end
end
while wait(0.5) do
followPlayer()
end