Trying to make a part follow the nearest player

local Players = game:GetService("Players")
local orbfollowdistance = 300
local followspeed = 0.04

local function findNearestPlayer()
	local nearest = nil
	local shortestdistance = orbfollowdistance
	for _, player in ipairs(game.Player:getchildren) do
		if 	player.Character and player.Character:FindFirstChild("HumanoidRootPart") then 
			local distance = (orb.Position - player.Character.HumanoidRootPart.Position).magnitude
			if distance < shortestdistance then
				shortestdistance = distance
				nearest = player
			end
		end
	end
	return nearest
end

local function followplayer()
	while true do
		task.wait()
		nearestdistance = findNearestPlayer()
		if nearestdistance then
			local playerpos = nearestdistance.Character.HumanoidRootPart.Position
			local orbpos = orb.Position
			local newpos = Vector3.new(playerpos.X, orbpos.Y, playerpos.Z)
			local movedirect = (newpos - orbpos).Unit
			local movedist = (newpos - orbpos).Magnitude
			orb.Position = orb.Position + (movedirect * movedist * followspeed)
		end
	end
end

task.spawn(followplayer)

A-here’s my current code

My code doesn’t work!
I tried looking for answers on the internet but I couldn’t find anything!

1 Like

Please send the code using "```

First of all change line 9 from game.Players:getchildren() to → Players:getchildren since the service is already defined. Second of all findNearestPlayer where nearestdistance is being used instead of nearest. The distance was being assigned to nearestdistance instead of nearest, which is being returned as the player. Finally In the followplayer function, the variable nearestdistance should be renamed to match the return value from findNearestPlayer (nearest).

1 Like

Here’s the updated code.

local orb = script.Parent
local Players = game:GetService("Players")
local orbfollowdistance = 300
local followspeed = 0.04

local function findNearestPlayer()
	local nearest = nil
	local shortestdistance = orbfollowdistance
	for _, player in ipairs(Players:GetChildren()) do
		if player.Character and player.Character:FindFirstChild("HumanoidRootPart") then
			local distance = (orb.Position - player.Character.HumanoidRootPart.Position).magnitude
			if distance < shortestdistance then
				shortestdistance = distance
				nearest = player
			end
		end
	end
	return nearest
end

local function followPlayer()
	while true do
		task.wait()
		local nearestPlayer = findNearestPlayer()
		if nearestPlayer then
			local playerPos = nearestPlayer.Character.HumanoidRootPart.Position
			local orbPos = orb.Position
			local newPos = Vector3.new(playerPos.X, orbPos.Y, playerPos.Z)
			local moveDirect = (newPos - orbPos).Unit
			local moveDist = (newPos - orbPos).Magnitude
			orb.Position = orb.Position + (moveDirect * moveDist * followspeed)
		end
	end
end

task.spawn(followPlayer)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.