Help with raycast

Whenever I call the castRay function it warns ‘No raycast result’ even though I thought I did it right. Im trying to make it so that when you look at a part in the Trees folder, it prints that you found a tree but it isn’t. I’m calling the function in a different script

local tool_handler = {}

local camera = workspace.CurrentCamera

local uis = game:GetService('UserInputService')

local rayOrigin = camera.CFrame.Position
local rayDirection = camera.CFrame.LookVector * 1000

local raycastParams = RaycastParams.new()
raycastParams.IgnoreWater = true
raycastParams.FilterDescendantsInstances = {workspace.Trees:GetChildren()}
raycastParams.FilterType = Enum.RaycastFilterType.Include

local raycastResult = workspace:Raycast(rayOrigin, rayDirection , raycastParams)

function tool_handler.castRay()
	if raycastResult then
print('Instance:', raycastResult.Instance)
 print('Found tree')
	else
		warn('No raycast result')
	end
end

return tool_handler

Try this:

local tool_handler = {}

local camera = workspace.CurrentCamera

function tool_handler.castRay()
local rayOrigin = camera.CFrame.Position
local rayDirection = camera.CFrame.LookVector * 1000

local raycastParams = RaycastParams.new()
raycastParams.IgnoreWater = true
raycastParams.FilterDescendantsInstances = workspace.Trees:GetChildren() -- No need to create an array here
raycastParams.FilterType = Enum.RaycastFilterType.Whitelist -- Changed to Whitelist

local raycastResult = workspace:Raycast(rayOrigin, rayDirection, raycastParams)

if raycastResult then
    print('Instance:', raycastResult.Instance)
    print('Found tree')
else
    warn('No raycast result')
end

end

return tool_handler

1 Like

It doesn’t work because you are raycasting ONCE right when the script runs, and try to use the raycastResult of that one single raycast in the function.

Try this:

local tool_handler = {}

local camera = workspace.CurrentCamera

local uis = game:GetService('UserInputService')

local rayOrigin = camera.CFrame.Position
local rayDirection = camera.CFrame.LookVector * 1000

local raycastParams = RaycastParams.new()
raycastParams.IgnoreWater = true
raycastParams.FilterDescendantsInstances = {workspace.Trees:GetChildren()}
raycastParams.FilterType = Enum.RaycastFilterType.Include


function tool_handler.castRay()
local raycastResult = workspace:Raycast(rayOrigin, rayDirection , raycastParams)

	if raycastResult then
print('Instance:', raycastResult.Instance)
 print('Found tree')
	else
		warn('No raycast result')
	end
end

return tool_handler

All you have to do is simply move the raycast operation inside the function .castRay()!

2 Likes

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