I want to have a NPC that is attempting to follow the player but only staying slightly away by a few studs, how do I do this?
How I would start: humanoid:MoveTo(rootPart.Position)
(humanoid for NPC, rootPart for player’s rootpart)
Since humanoids won’t utilize the Y coordinate in movement, I’d safely just want to have it studs way from the X, Z coordinates but without being disorientated so that its straight at the player.
I really don’t know where to start but I would guess trigonometry could be involved. It’s basically a NPC following a player without trying to touch the player.
I couldn’t find any topics on this via search so I am asking here.
--//Services
local Players = game:GetService("Players")
--//Variables
local NPC = nil -- ?
--//Functions
local function FindNearestPlayer()
local Closest = math.huge
local ClosestPlayer = nil
for i,v in pairs(Players:GetPlayers()) do
if v.Character:FindFirstChild("HumanoidRootPart") ~= nil then -- make sure they're existant
local Distance = v:DistanceFromCharacter(NPC.HumanoidRootPart.Position)
if Distance < Closest then
Closest = Distance
ClosestPlayer = v
end
if i == #Players:GetPlayers() then
return ClosestPlayer
end
end
end
end
--//Events
-- ?
--//Main
FindNearestPlayer() -- call it
That script right there just checks for nearest player, so you could just subtract their position for a little or use @Operatik’s method.
Yes, I do mean with an offset. I would like to know whether calculating where that offset position is or just stopping when they’re close enough is more efficient? I just want to know how to move to an offset position of the player for NPC to move to.
Both requires a loop and I’m not sure myself which one is more effective in performance. Try writing two versions if you have the time and effort for it.
But while it works, it causes the NPC to start shaking sideways based on how unstraight the player is moving, without any shaking if the player moves in a straight line, how would I fix that?