Worldroot:Raycast() fails to return any hit instances

Hello! I’m trying to build a raycasting gun right now. When I try to test it with this code, nil is returned 99% of the time. Even when, based off of my visualization, the ray hits a part. I experimented with the filter and that didn’t seem to affect anything.

Visualization -
https://gyazo.com/6b227ede248766edbf8ad9e2015fbafd

Occasionally, the correct part is returned. I can’t find a trigger for when it is printed, however. There are no errors. The mouseHit parameter references (mouse.Hit.CFrame.p) and origin is (tool.Handle.Position).

local module = {}

--//Services
local runService = game:GetService("RunService")

--//Void; Raycast from gun to mousePos with 300 stud constraint
function module:CastRay(origin, mousePos, tool, plr, murderer)
    
    --//Cast ray; Ignore character and tool
    local rayParams = RaycastParams.new()
   	rayParams.FilterDescendantsInstances = {plr.Character, workspace.Rays}
    rayParams.FilterType = Enum.RaycastFilterType.Blacklist
    local raycastResult = workspace:Raycast(origin, mousePos * 300, rayParams)
    
    --//Check for a hit
    if raycastResult then
        local hitPart = raycastResult.Instance
        print(hitPart)
    else
        print("Nothing was hit.") -- This is printed most of the time
    end
    
    --//Visualize ray
    local rayPart = Instance.new("Part")
    rayPart.Anchored = true
    rayPart.CanCollide = false
    rayPart.Size = Vector3.new(0, 0, (origin - mousePos * 300).magnitude)
    rayPart.CFrame = CFrame.new(origin, mousePos)
    rayPart.Parent = game.Workspace.Rays
    
end

return module

Thank you for your time!

The second argument should be a direction not a position. You can create a direction by

goal - origin

Then normalizing it and multiplying by your desired distance.

(goal - origin).Unit*300 -- 300 studs long
2 Likes

Thank you! I actually did this but did (origin + goal) which didn’t help. I appreciate your quick help.

One more question- I’m having trouble with visualizing the part. This is the iteration that’s been closest.

    rayPart.Size = Vector3.new(0, 0, ((mousePos - origin).unit * 300).magnitude)
    rayPart.CFrame = CFrame.new(((mousePos - origin).unit * 300)/2, origin)

https://gyazo.com/59777885d8db9a458e28e7ae1c934615

As you can see, it is not directly going towards the mouse. It also goes behind, which I thought was due to the part being the handle, but even when changing that it did not fix it.