Raycast only works at certain angles?

As you can see in the video, the player will move around and point their locked mouse towards an object. It is very inconsistent, which is caused by it only being detected at certain angles. The hitbox I made should be equally big on all sides. My question is how would I fix this so it works at all angles?
Script is below video.
ezgif.com-video-to-gif (1)

local player = game.Players.LocalPlayer
local char = player.Character or player.CharacterAdded:Wait()
local cam = workspace.CurrentCamera

local uis = game:GetService("UserInputService")
local rs = game:GetService("RunService")
local remoteEvent = game:GetService("ReplicatedStorage").remoteEvents.destroyer

local params = RaycastParams.new()
params.FilterType = Enum.RaycastFilterType.Exclude
params.FilterDescendantsInstances = char:GetDescendants()
params.FilterDescendantsInstances = game.Workspace.id1Spawns:GetDescendants()

local function CreateRayCast()
	local mousePos = uis:GetMouseLocation()
	local rayCast = cam:ViewportPointToRay(mousePos.X,mousePos.Y)
	local rcResult = workspace:Raycast(rayCast.Origin,rayCast.Direction * 20,params)
	return rcResult
end

rs.RenderStepped:Connect(function()
	local result = CreateRayCast()
	if result and result.Instance then
		local item = result.Instance:FindFirstAncestorWhichIsA("Model")
		if item.Parent == game.Workspace.items then
			print(item)
			script.Parent.Parent.PlayerGui.CollectGui.Enabled = true
			--remoteEvent:FireServer(item)
		else
			script.Parent.Parent.PlayerGui.CollectGui.Enabled = false
		end
	else
		script.Parent.Parent.PlayerGui.CollectGui.Enabled = false
	end
end)	

Here is the hitbox visualized. You can see I’m hitting it from both sides, but it only works from the lower side.
image
image

Apparently there is something called “depth” which I cannot find any information about other than in studio itself (doesn’t seem to be in tutorial videos or on the roblox-studio documentation website). Just stumbled upon it while looking through parameters. Setting it to 5 seems to have a very positive effect, causing it to work very well. While setting it to 1 only improves it by a little, and setting it to 30 makes it glitchy. I’m not sure what this “depth” parameter is, but it does work now.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.