Detecting nearest Player

Greetings, I am making a local script that consists of shooting a coin that will reflect to someone. I was able to make the entire tossing and shooting part but I have no idea where to start when it comes to detecting the nearest Player. Plus, I don’t want to detect NPCs, just players.

Here is a part of my code that I want to implement the Player detection.

Any help is welcome.

		while wait() do
			inputservice.InputBegan:Connect(function(shoot)
				if shoot.KeyCode == Enum.KeyCode.F and value2 == false then
					value2 = true
					
					--fires ray
					local raycastParams = RaycastParams.new()
					local firerayorigin = character.Head.Position
					local fireraydirection = game.Workspace.CurrentCamera.CFrame.LookVector
					local lookdirection = game.Workspace.CurrentCamera.CFrame.LookVector
					
					--gets raycast result
					local rayresult = workspace:Raycast(firerayorigin, fireraydirection*50, raycastParams)
				
					if rayresult.Instance == coin then --coin hitted, locating humanoids
						--detecting nearest humanoid
						--damages the nearest humanoid
						print("Hitted")
						coin:Destroy()
						
					else
						print("Missed")
		end
	end	
end)
3 Likes

You can use

for i,v in pairs(game.Players:GetPlayers()
    local HumanoidRootPart = v.Character.HumanoidRootPart
    if HumanoidRootPart.Position = TheRangeOfActivating then
        --Do your script in here
    end
end

EDIT: I’m not that experienced in the magnitudes but that’s basically what I would have used.

Using for i,v in pairs(game.Players:GetPlayers() will make the local in local HumanoidRootPart = v.Character.HumanoidRootPart highlighted, resulting in an error.
The correct form would be for i,v in pairs(game.Players:GetPlayers()) do.

One change that I made regarding your code is removing the magnitude since I don’t really have any plans for a “limit”.

Another thing that I want to point out is that I putted a print(HumanoidRootPart.Parent) to see who the coin reflected to. The problem being is that it reflects to the own player who throwed it. And when testing in a local server with 2 players I found out that the coin reflects to both players.
^I was able to fix this problem by adding the if HumanoidRootPart ~= player.Character.HumanoidRootPart then.

Also dont forget to put double equals (==) when using if, it happens to me too. :wink:

I will give you the solution because with a few modifications to your code I might be able to do the rest, thank you very much.

1 Like

Oh ok glad to help at least and I just noticed I didn’t use double equal signs.

1 Like