How to make NPC follow player but by some studs away?

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.

5 Likes

This is very simple.

--//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.

4 Likes

Perhaps if I mapped this out, would it help?

  • The NPC checks distance between player and itself
  • Get position and utilize a “local” space method to acquire the offset, based on orientation
  • The NPC moves to the target location

Alternatively:

  • The NPC checks distance every X rate
  • If the NPC is within distance, stop moving
  • If the NPC is not within distance, move to the target

@Kensizo I think he meant by NPC following the player but with an offset, spacing between.

4 Likes

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.

1 Like

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.

2 Likes

I tried to use:

closestPlayerPosition - (humanoid.RootPart.CFrame.LookVector*4)

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?