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

How can I set the raycast destination to the position of the mouse currently?

In the script below, how can I set rayDest to where my mouse is pointing? I've tried GetMouse for what I am trying to do but it didn't work in-game.

local tool = script.Parent.Parent
local rayDest = Vector3.new(0, 100, 0)

function onActivation()
    local ray = Ray.new(script.Parent.Position, rayDest)
	local hit,position = workspace:FindPartOnRayWithIgnoreList(ray, {script.Parent})
	if hit then
		print(hit.name)
	end
end
 
tool.Activated:Connect(onActivation)

1 answer

✓ Accepted answer

Edited code so it should work now

The mouse object has a property called Hit, which returns a CFrame position on where the player clicked. If CFrames don’t work though, you can convert it into a Vector3 by using Mouse.Hit.Position or Mouse.Hit.p (I recommend using .Position as I can’t find .p anywhere except in a couple of tutorials, so I’m assuming .p is deprecated).

Here’s what your code should look like :

local tool = script.Parent.Parent
local rayDest = Vector3.new(0, 100, 0)
local Mouse = game:GetService('Players').LocalPlayer:GetMouse()

local function onActivation() -- Recommended to put "local" before functions
    rayDest = (Mouse.Hit.Position - script.Parent.CFrame.Position).Unit * 100 --Gets the "direction" of the ray
    local ray = Ray.new(script.Parent.Position, rayDest)
    local hit,position = workspace:FindPartOnRayWithIgnoreList(ray, {script.Parent})
    if hit then
        print(hit.Name)
    end
end

tool.Activated:Connect(onActivation)

Hope this helped!

2 comments

0

It doesn't work in-game.

0

^ I’ll try to find the problem and fix it soon, but for now you’ll have to wait.

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