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

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

Asked by 4 years ago

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)
0
is the script a Local Script? ryan32t 306 — 4y

1 answer

Log in to vote
0
Answered by
Benbebop 1049 Moderation Voter
4 years ago

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)
Ad

Answer this question