Make NPC stay certain distance from target

Like instead of walking all the way up to the target, I want them to walk up to them but stay a few studs away. Is there a way to calculate that?

Picture Example:

The top picture is what happens normally. The bottom picture is what I want to happen, the blue circle is the distance it should stop from the target.

Script:

while wait() do
	if ClosestPlr.Value ~= nil then -- If a player is nearby

		local Player = ClosestPlr.Value.Character
		local PlayerHRP = Player:WaitForChild("HumanoidRootPart")

		local Goal = Vector3.new(PlayerHRP.Position.X,0,PlayerHRP.Position.Z)

		local Path = PFServ:CreatePath(PathArgs)

		Path:ComputeAsync(hrp.Position,Goal) -- Start & End Position

		local waypoints = Path:GetWaypoints() -- Gets Points

		if Path.Status == Enum.PathStatus.Success then
			
			for i,waypoint in pairs(waypoints) do
				
				if waypoint.Action == Enum.PathWaypointAction.Jump then
					hum.Jump = true
				end
				
				hum:MoveTo(waypoint.Position)

			end
		end
	end
end

Use (VectorA - VectorB).Unit as a factor to get one studs in the direction between them and multiply it with the desired distance apart. If they run them over, swap the vectors or change the additive factor to subtractive factor instead. Then using the new calculated position, set the goal there.

You’d want to use the magnitude of two vectors to determine if the AI should keep moving or not.

To get the magnitude, you can use (EndPosition - StartPosition).Magnitude. This will return a number which represents the distance. You can set a max distance variable and do the following:

local MaxDistance = 8;

-- Check if the AI is not within max Distance.
if (EndPosition - StartPosition).Magnitude < MaxDistance then
    hum:MoveTo(waypoint.Position)
else -- Distance from AI is below the maximum distance.
    -- Stop your AI from moving.
end

You would have to monitor the AI’s distance and stop it from moving when it’s below the maximum distance. You can do it through some event listener, loop or a separate thread.

4 Likes