Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

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

Asked by
RedCombee 585 Moderation Voter
10 years ago

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

1 answer

Log in to vote
7
Answered by
jobro13 980 Moderation Voter
10 years ago

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.

0
You have a syntax error; last line needs a paren. Also, you should mention ClickDetectors; the most straightforward way to do this. TheLuaWeaver 301 — 10y
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... jobro13 980 — 10y
0
True. I do not want the cursor to change at all. RedCombee 585 — 10y
0
What about plr:DistanceFromCharacter()? 0xDEADC0DE 310 — 8y
Ad

Answer this question