Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to make something target the nearest player?

I tried to create something that targets the nearest player. I don't know how to target the nearest player, but I got the path finding thing down.

Here's what I've got so far:

for i,v in pairs(workspace:GetChildren()) do
	if v:FindFirstChild("HumanoidRootPart") then
		if v.HumanoidRootPart.Position.Magnitude <= 15 then
			local HRP = v.HumanoidRootPart
			local OHRP = script.Parent.HumanoidRootPart
			local human = script.Parent.Humanoid
			
			local path = game:GetService("PathfindingService"):FindPathAsync(OHRP,HRP)
			local points = path:GetWaypoints()
			
			if path.Status == Enum.PathStatus.Success then
				for i,v in pairs(points) do
					human:MoveTo(v.Position)
					human.MoveToFinished:Wait()
					if v.Action == Enum.PathWaypointAction.Jump then
						human.Jump = true
					end
				end
			end
		else
			wait()
		end
	end
end

1 answer

✓ Accepted answer

The function you'd want to use here is GetPlayerFromCharacter(), which is called from the Players service. If it finds a player associated with what you give it, it returns that player. Otherwise, the function returns nil.

What I suggest doing is to define an empty variable on the lowest scope (which would be before every loop and function in your script):

local player -- This variable is currently nil, but will be assigned later

Then, before you start your magnitude loop, use a loop like this to set player to a valid player:

for _, inst in pairs(workspace:GetChildren()) do
	if game.Players:GetPlayerFromCharacter(inst) then
		player = inst
		break
	end
end

Then, in your magnitude loop, you should compare the distance between the player and the object:

if (player.HumanoidRootPart.Position - v.HumanoidRootPart.Position).Magnitude <= 15 then
	-- Do other stuff
end

Doing just v.HumanoidRootPart.Position will not make it follow the player like you'd want it to.

1 comment

0

Thanks! WIll try it later!

This discussion is preserved as it was. New answers, comments, and votes are closed.