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

How to check using a tool, if the click target was in a player?

I need to make a tool that when clicking it, make sure the location where the click was corresponds to a player. I know that to check a player just use FindFirstChild ("Humanoid") however I do not know how to find the target of the mouse.

2 comments

1

Can you include the script you are using.

0

2 answers

Basics


Well there are two things that make this extremely easy, the Activated event of the tool, which fires when you click it with the tool equipped and the Target property of the player's mouse, which gets what the mouse it pointing at . However, if whatever it is pointing to is > 1000ish studs away, it will return nil.

Activated :

tool.Activated:Connect(function()
	...
end)

Another useful thing


Another thing that will be handy is the GetPlayerFromCharacter function of the players service. This is good for getting the player from a character, as the name entails. Since body parts are parented to the player's character, this will come in handy.

Application


There are a couple of things your script should accomplish;

  1. Establish a tool variable, a player variable and a mouse variable in case you have to use it later on

  2. Listen to the activated event of the tool so you know when its clicked

  3. Get the Mouse target, and check if there is one

  4. Check if it is a body part of a player

  5. Whatever you want to do :p

In a local script:

local tool = script.Parent
local plr = game.Players.LocalPlayer
local mouse = plr:GetMouse()--step1

tool.Activated:Connect(function()--step2
	local target = mouse.Target 
	if target then --step 3  
		if game.Players:GetPlayerFromCharacter(target.Parent)  then--step4
			--step 5
		end
	end
end)

Addition: you could have done

if target and game.Players:GetPlayerFromCharacter(target.Parent)  then

end

instead of what I did

mouse.Hit.p would be the formula to get the location, only you cannot exactly check if it was a player as the mouse is abstract, it's best to use a CasyRay to follow the CFrame to check whether or not it touched a Player

Eg.

local Player = game:GetService("Players").LocalPlayer
local mouse = Player:GetMouse()

mouse.Button1Down:Connect(function() --// Button1 is left click, Button2 is right click, and Button3 is wheel.
	local mousePos = mouse.Hit.p
end)

Hope this helps

2 comments

0

Button1 is left click, Button2 is right click and Button3 is wheel click, did you mean that?

0

Yeah, not sure why that happened, wait..

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