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!