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

How do i find the nearest player?

so i have this boss that i want to have this attack go to the nearest part inside the player character its welded to the characters feet called Target and i want the KingTargetCircle to move the the nearest Target and stay there. How would that work? anyways here is the script.

while true do

game.Workspace.KingAttackCircle.Position = game.Workspace:FindFirstChild("PlayerCharacter").Target.Position

wait(1)

game.Workspace.KingAttack.Position = game.Workspace.KingAttackCircle.Position

game.Workspace.KingAttack.Transparency = .5

wait(.1)

game.Workspace.KingAttack.Transparency = .6

wait(.1)

game.Workspace.KingAttack.Transparency = .7

wait(.1)

game.Workspace.KingAttack.Transparency = .8

wait(.1)

game.Workspace.KingAttack.Transparency = .9

wait(.1)

game.Workspace.KingAttack.Transparency = 1

wait()

game.Workspace.KingAttack.Position = game.Workspace.KingOG.Position

wait(2)

end

1 comment

0

use workspace.kingattack.transparency = workspace.kingattack.transparency + 0.1 (best used in for loops)

1 answer

✓ Accepted answer

Get all players and their characters. Iterate through all characters and check which root part is closest.

local MyRoot = script.Parent:FindFirstChild('HumanoidRootPart');
function Nearest(radius)
	radius = radius or math.huge; --if radius unset, then set it to math.huge
	local ClosestRoot = {Root = nil; Radius = nil;} --the tab we'll be using to set the root n stuff
	for i, v in pairs(game.Players:GetPlayers()) do --iterate over players
		if (v.Character) then --if the character is loaded
			local Root = v.Character:WaitForChild('HumanoidRootPart'); --wait for the root
			local Distance = math.abs((MyRoot.Position-Root.Position).magnitude); --get a positive distance value
			if (Distance <= radius) then --if the dist is lower than the set radius
				if (not ClosestRoot.Root) then --if there is no closest root, then
					ClosestRoot = {Root = Root; Radius = Distance}; --set the tab
				elseif (ClosestRoot.Radius >= Distance) then --otherwise
					ClosestRoot = {Root = Root; Radius = Distance}; --y'know
				end
			end
		end
	end
	return ClosestRoot; --returns the root and radius
end

I wrote this all in StackEdit so I'm completely unaware if there are any errors. If there are, please let me know. :P

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