Raycast returns nil

Didn’t find a post with a valid solution, so here:

function RoundHandler.RegisterShot()
	local viewPort = camera.ViewportSize / 2
	local origin = camera.CFrame.Position
	local direction = (camera.CFrame * CFrame.new(Vector3.new(viewPort.X, viewPort.Y, 0))).LookVector
	local params = RaycastParams.new()
	params.FilterDescendantsInstances = {Players.LocalPlayer.Character}
	params.FilterType = Enum.RaycastFilterType.Blacklist
	local result = workspace:Raycast(origin, direction, params)
	print(result)
end

image
For some reason it is nil, don’t comprehend why. Raycast documents are too confusing for me.

Hey there,

if the :RayCast(...) returns nil, it means that it hasn’t intersected with anything thus returning nil.
Maybe check if you’re sending the ray in right direction or it is long enough.

Maybe try visualizing the raycast to see how long it is or which direction it aims.

EDIT:

The direction variable seems to be too short, you’re only getting the .LookVector (look vectors have length of 1 stud), maybe try multiplying the whole direction with some magic number.

2 Likes

Oh.

Except, that only worked once. Consecutive attempts at raycasting return nil, again (applied your edit as solution, btw)

Yup! Now it’s simple to use the RaycastResult.

RaycastResult.Instance - It’s the instance that intersected with the raycast.

For more info:

Oh, what number are you multiplying it with. It can be a littly tricky since the camera position could be x studs away from the instance, so either try doing some math or send the raycast on a really long trip :smiley:

Assuming I did it incorrectly: local direction = (camera.CFrame * CFrame.new(Vector3.new(viewPort.X, viewPort.Y, 0))).LookVector * 100.

Well,
yeah,
I mean, I multiplied everything.

Yes that’s what I meant, the thing behind this is that if the camera is 101 studs away from everything, it won’t intersect with anything.

image
It does work, however…
Hitting the three red parts return nil, but not when I hit the white part. Both have the same, except size, properties.

Nevermind. My issue is solved but I have another one now. Since it’s no longer related I’ll close this topic.

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