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

How do I make something occur when a player clicks on a part of another player within 20 studs?

I have some ideas, but everything I try won't work. Any idea?

1 answer

✓ Accepted answer

You need two things:

  • A way to get if someone clicks a part of a player
  • A way to get if this part is closer than 20 studs

The first one is simple: if the part's parent has a humanoid AND game.Players:GetPlayerFromCharacter(target.Parent) returns something, you know it's a "character part".

function CheckPlayerPart(target)
	if target.Parent:FindFirstChild("Humanoid") then
		return game.Players:GetPlayerFromCharacter(target.Parent) ~= nil
	end
	return false
end

To check if something is close, you can use a trick with positions. The "magnitude" of a vector returns the length of it - if you subtract the position of the player and the position of the part you get a new vector defining the offset of that player part: the length is the distance (this always is a positive value).

function GetInrange(part)
	return (part.Position - game.Players.LocalPlayer.Character.Torso.Position).magnitude >20 
end

And to put it all together:

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

function Check(target)
	if not target then
		return false
	end
	return GetInrange(target) and CheckPlayerPart(target)
end

mouse.Button1Click:connect(function()
	if Check(mouse.Target) then
		-- do stuff
	end
end)

You also need to provide - in the same script - the functions described above.

4 comments

0

You have a syntax error; last line needs a paren. Also, you should mention ClickDetectors; the most straightforward way to do this.

1

Thanks, true. ClickDetectors for this!? Okay, indeed, they have a range property. But you need to add 6 * number of players of ClickDetectors and moreover your cursor changes too - not sure if asker wants that...

0

True. I do not want the cursor to change at all.

0

What about plr:DistanceFromCharacter()?

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