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 code execute on player click?

How can I make a script that when you click on a player with your mouse within a certain range (optional) code is executed? It's pretty self forward, but I still don't know how to do it. Please at least give me SOME, brief explanation or just do the script for me, which will be greatly appreciated.

1 answer

✓ Accepted answer

Local Script

local player = game.Players.LocalPlayer
local part = workspace.Part

game:GetService("UserInputService").InputBegan:Connect(function(input, event)
	if input.UserInputType == Enum.UserInputType.MouseButton1 then
		local distance = (player.Character.HumanoidRootPart.Position - part.Position).magnitude
		if distance < 50 then
			print("InRange")
		end
	end
end)

Using the UIS (UserInputService) we can determine if the player clicks the mouse using the UserInputType.MouseButton1.

Next, to determine the distance from a part (mine is defined above as workspace.Part), we use .magnitude on the position between the player's HumanoidRootPart (PrimaryPart) and the part.

Finally, if the distance is below a certain number (in this case, 50), then the event will fire.

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