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

how to aim raycasting at where the mouse is pointed?

so i am using raycasting to script a gun i just started on the gun and i want it to check if a player clicked then the ray goes. The code is this,

local maxdistance = 500
script.Parent.Parent.Equipped:Connect(function(mouse)
	local ray = Ray.new(script.Parent.Parent.barrel,i don't know what to put here i don't know how to have the orientation be where the mouse is)
end)

so yeah how do you get the orientation to put the ray at? (i need it to go to the mouse)

1 answer

✓ Accepted answer

I assume you have a "barrel" script.Parent.Parent.barrel. The direction from the barrel to the mouse will be as follows:

-- PS: You shouldn't be using the mouse provided from Equipped, but I'll use it anyway for the sake of it working.
local maxdistance = 500
local myMouse
local barrel = script.Parent.Parent.barrel

script.Parent.Parent.Equipped:Connect(function(mouse)
	myMouse = mouse
end)

script.Parent.Parent.Activated:Connect(function()
	if myMouse then
		local dir = (myMouse.Hit.Position - barrel.Position).Unit
		-- Grabs the direction of the barrel to the mouse position. Multiply this by some number to make the ray length.
		local ray = Ray.new(barrel.Position, dir)
	end
end

4 comments

0

what does the .unit at the end of line 12 mean?

0

That gets the direction of the vector going from barrel -> myMouse.

0

at line 12 it has an error when i click it, it says "this mouse is no longer active"

0

also is it suppose to be in a script, or a local script?

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