Sending a ray towards the mouse

Hello devforum,

It seems that i’ve managed to create my raycast gun with a few hitches:

local function active()
print('e')
local attachment1 = Instance.new("Attachment")	
attachment1.Parent = tool.Barrel
local attachment2 = Instance.new("Attachment")
attachment2.Parent = workspace.Baseplate
attachment2.Position = mouse.hit.p
local beam = Instance.new("Beam", workspace)
beam.Attachment0 = attachment1
beam.Attachment1 = attachment2
beam.Enabled = true
local raycastResult = workspace:Raycast(tool.Barrel.Position, mouse.hit.p)
print(raycastResult)
wait(1)
beam:Destroy()

end

this is only the start, but i’d say it’s pretty good; what i’m looking for help on is sending the beam DIRECTLY to the mouse, as my solution makes it sag a bit when i shoot anywhere but empty void


(notice the bottom beams; I was shooting much farther , about halfway the top beams)

The second argument required for the WorldRoot:Raycast method is a direction unit, not a position.
To get the direction unit from two V3 positions, you would need to subtract one from another and get the .unit of the V3 result then multiply the direction unit by the distance you would like for the ray to cast.

local origin = tool.Barrel.Position
local point = mouse.Hit.p

local distance = (origin - point).magnitude -- (studs) can also be a constant such as 100
local direction = (point - origin).unit * distance

local raycastResult = workspace:Raycast(origin, direction)
2 Likes