Trying to detect if player is in proximity to another player

when i press E on my keyboard, it should loop through other players to see if the player exists and if it finds a player within distance of the player that pressed E, it will tell the distance between the two players.

error:


image

local script:

local pickupPlayerEvent = game.ReplicatedStorage:WaitForChild("pickupPlayerEvent")
local uis = game:GetService("UserInputService")

uis.InputBegan:Connect(function(input, gameproc)
	if input.KeyCode == Enum.KeyCode.E then
		print("pressed e")
		local myHRP:MeshPart = game.Players.LocalPlayer.Character:WaitForChild("HumanoidRootPart")
		pickupPlayerEvent:FireServer(myHRP)
		print("Firing...")
	end
end)

script:

local pickupPlayerEvent = game.ReplicatedStorage:WaitForChild("pickupPlayerEvent")

pickupPlayerEvent.OnServerEvent:Connect(function(myplr, myHRP:MeshPart)
	for _, otherPlr in ipairs(game.Players:GetPlayers()) do
		local otherCharacter = otherPlr.Character
		if not otherCharacter then continue end
		local otherHRP:MeshPart = otherCharacter:WaitForChild("HumanoidRootPart")
		if not otherHRP then continue end
		
		local dist = (otherHRP - myHRP).Magnitude
		if dist < 10 then
			print(string.format("%s is close (%.1f studs away)", otherPlr.Name, dist))
		end
	end
end)

You need to use the position of each hrp.

1 Like

ty for ur help byte. i changed up the code but it keeps throwing me errors tho.

local pickupPlayerEvent = game.ReplicatedStorage:WaitForChild("pickupPlayerEvent")

pickupPlayerEvent.OnServerEvent:Connect(function(myHRP:MeshPart)
	for _, otherPlr in ipairs(game.Players:GetPlayers()) do
		local otherCharacter = otherPlr.Character
		if not otherCharacter then continue end
		local otherHRP:MeshPart = otherCharacter:WaitForChild("HumanoidRootPart")
		if not otherHRP then continue end
		
		local dist = (otherHRP.Position - myHRP.Position).Magnitude
		if dist < 10 then
			print(string.format("%s is close (%.1f studs away)", otherPlr.Name, dist))
		end
	end
end)

i also tried (otherHRP.CFrame- myHRP.CFrame) but no luck

You omitted myplr from the event function. The player who fired a remote event to the server is always the first argument of it. Add it back in and it should stop thinking myHRP is the player.

1 Like

absolutely perfect, im so stiff. thanks a million for your help. ur a legend man :slight_smile:

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