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

Is it possible to limit the distance for Button1Down?

For example, the code below. If you click your mouse while over the Hitbox, the GUI appears. However, if you are 100 studs away and click the part, the GUI will still appear.

mouse.Button1Down:Connect(function()
	if mouse.Target.Name == "Hitbox" then
		interactions.Visible = true
	else
		interactions.Visible = false
	end
end)

Is there anyway to limit the distance somehow? As in the GUI will only open if the player is within 5 studs of the object. I know I could use ClickDetectors, but for the task I'm trying to do it really isn't the most efficient option... thanks!

1 answer

✓ Accepted answer

It is possible to lower the distance that things will happen if you have your character's position and the location they are interacting with. You would want to most likely use magnitude in order to get this distance. Roblox does have some information on magnitude which can be found here.

player = game.Players.LocalPlayer
mouse = player:GetMouse()

mouse.Button1Down:Connect(function()
	local magnitude = (player.Character.Torso.Position - PartYouAreTouching.Position).magnitude --Distance
	if magnitude <= 5 then --Value of studs
	    if mouse.Target.Name == "Hitbox" then
	        interactions.Visible = true
	    else
	        interactions.Visible = false
	    end
	end
end)

Please remember to accept my answer if this helps solve your problem. If I have made a mistake or my solution does not work, please feel free to message me or comment on to my answer. Thanks!

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