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

Trying to use a Ray to determine what the player clicked on in the workspace. What am I doing wrong?

I am trying to make a gathering tool, to take a part that the player clicks on while the tool is equipped, and if certain specifications are met, such as the name of the part, then it starts the animation and etc. However for now I am just trying to determine how to get the script to print the name of the part that the player clicks on.


local function getmouse() -- this code i got from a help question, never used rays before
	local cursorPosition = game:GetService("UserInputService"):GetMouseLocation()
	local oray = game.workspace.CurrentCamera:ViewportPointToRay(cursorPosition.x, cursorPosition.y, 0)
	local ray = Ray.new(game.Workspace.CurrentCamera.CFrame.p,(oray.Direction * 1000))
	return workspace:FindPartOnRay(ray)
end 

script.Parent.Activated:Connect(function() -- script.Parent is a tool
	print(getmouse());
end)

1 comment

0

is the script a Local Script?

1 answer

This can be done much more easily without direct use of rays using Mouse.Target.

Ex.

mouse.Button1Down:Connect(function()
	if mouse.Target then
		print(mouse.Target.Name)
	end
end)

the if statement makes it so that it does not print nil when the mouse is not pointed at anything

An if statement will allow you to sort out whatever you want.

Ex.

mouse.Button1Down:Connect(function()
	if mouse.Target.Name = “SelectBasePart” then
		print(mouse.Target.Name)
	end
end)

For multiple BaseParts use a table of names.

Ex.

local SelectBaseParts = {Part1, Part2, Part3}

mouse.Button1Down:Connect(function()
        for i = 1, #SelectBaseParts do
	        if mouse.Target.Name = SelectBaseParts[i] then
		        print(mouse.Target.Name)
                end
	end
end)

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