im using a script to make an NPC follow the player. Im trying to make the NPC follow the player, but stay at a certain distance from the player. like this...
if the player walks away, the NPC gets closer, if the player gets closer, the NPC moves farther away...to maintain the same distance from the player
local Mroot = script.Parent.HumanoidRootPart
local h = script.Parent.Humanoid
local Mspawn = script.Parent.Parent.MobSpawn.CFrame
--Finds a player that is in range
--use "local player = findplayer()"
function findplayer()
for _,v in next, game.Players:GetPlayers()do
if v.Character then
local char = v.Character
if char:FindFirstChild("Humanoid")and char:FindFirstChild("HumanoidRootPart")then
local pRoot = char.HumanoidRootPart
if (pRoot.Position - Mroot.Position).magnitude <= 40 then
return v
end
end
end
end
return nil
end
while wait() do
local player = findplayer()
if player ~= nil then
local stayat = CFrame * CFrame.new(0,0,-20)
h:MoveTo(player.Character.HumanoidRootPart.Position)
else
h:MoveTo(Mspawn.p)
end
end
ive tried doing this...
while wait() do
local player = findplayer()
if player ~= nil then
local stayat = player.Character.HumanoidRootPart.CFrame * CFrame.new(0,0,-20)
h:MoveTo(stayat.p)
else
h:MoveTo(Mspawn.p)
end
end
The NPC keeps the distance away from the player, but it tries to stay directly in front of the player... like this...
how do i make the NPC walk straight at the player, but stop at a certain distance...and if the player gets closer, walk away from the player, and remain the distance

2 comments
Blank images
ok fixed