Raycast is returning nil instead of correct part

What do you want to achieve?
I’m trying to make the character rotate to face wherever the mouse.Hit is on the screen. I also want the mouse to ignore any parts I have tagged as “InvisiCamEnabledPart”, and just target the parts underneath them.

I realised I can’t really use filtering on Mouse.Hit so I’ve been trying to use raycasting instead but it isnt really working out.

What is the issue?
I have the character rotating towards the mouse working just fine, but the issue is when I try to use raycasting and filtering to ignore the tagged parts. The raycast will usually be fine when I aim the mouse at the floor, but when I aim the mouse at any tagged parts, it just returns nil. Ideally, the raycasting should be returning the floor underneath the tagged part.

What solutions have you tried so far?

Here's my localscript that I'm using in StarterCharacterScripts:
local RunService = game:GetService("RunService")
local CollectionService = game:GetService("CollectionService")

local player = game:GetService("Players").LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local root = character:WaitForChild("HumanoidRootPart")

local camera = workspace.CurrentCamera
local mouse = player:GetMouse()

RunService.Stepped:Connect(function()
	-- raycast
	local ignoreList = CollectionService:GetTagged("InvisiCamEnabledPart")
	table.insert(ignoreList, character)
	
	local rayOrigin = camera.CFrame.Position
	local rayDirection = mouse.Hit.Position - camera.CFrame.Position
	local raycastParams = RaycastParams.new()
	raycastParams.FilterDescendantsInstances = ignoreList

	local raycastResult = workspace:Raycast(rayOrigin, rayDirection, raycastParams)
	print(raycastResult) -- This prints nil when my mouse is over tagged parts for some reason?
	
	local targetPosition = raycastResult and raycastResult.Position or mouse.Hit.Position
	
	-- rotate rootpart
	local forwardVector = (root.Position - targetPosition).Unit
	local rightVector = forwardVector:Cross(Vector3.new(0,1,0))
	local cframe = CFrame.fromMatrix(root.Position, -rightVector, Vector3.new(0, 1, 0))

	character.HumanoidRootPart.CFrame = cframe
end)

I’m hoping someone could help me figure out why my raycasting isnt working as I want it to, or any better ways I could achieve my goal? I’m still learning lol. Thank you :slight_smile:

Its probably the Range of your Ray cast, you would need to multiply the Direction.

2 Likes

I multiplied the direction of the raycast by 30 and it looks like its working now! I didn’t know the direction also included a range in it as well, so thank you! I’ll keep that in mind.

1 Like

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