Mouse Distance Detection not working

I’m trying to make it so if a player is within 50 meters of the mouse it teleports to them. However nothing happens I tried printing distance and nothing prints. The only think that prints is the mouse position and No player within 50 meters of the click position.

local Players = game:GetService("Players")
local localPlayer = Players.LocalPlayer
local mouse = localPlayer:GetMouse()
local maxDistance = 50

local function onMouseClick()
	-- Ensure the mouse hit target is valid
	if not mouse.Target then
		print("Mouse target not valid.")
		return
	end

	-- Get the position where the mouse clicked
	local targetPosition = mouse.Hit.Position

	print("Mouse clicked at position:", targetPosition)

	local playerFound = false

	-- Check for other players within 50 meters
	for _, player in pairs(Players:GetPlayers()) do
		if player ~= localPlayer then
			print("Checking player:", player.Name)

			if player.Character and player.Character:FindFirstChild("HumanoidRootPart") then
				local characterPosition = player.Character.HumanoidRootPart.Position
				local distance = (characterPosition - targetPosition).Magnitude
				
				
				
				print(distance)
				print("Distance to", player.Name, ":", distance)

				if distance <= maxDistance then
					playerFound = true
					-- Teleport the local player to the mouse position
					if localPlayer.Character and localPlayer.Character:FindFirstChild("HumanoidRootPart") then
						localPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(targetPosition)
						print("Teleported to:", targetPosition)
						break
					end
				end
			else
				print(player.Name, "does not have a Character or HumanoidRootPart.")
			end
		end
	end

	if not playerFound then
		print("No player within 50 meters of the click position.")
	end
end

mouse.Button1Down:Connect(onMouseClick)

That’s because in this line of code, if player ~= localPlayer then, you check if the player is NOT the local player, and assuming you are testing this solo in Roblox studio, nothing would print or occur, as it is only one player.

1 Like