Raycast isn't detecting the object that it's pointing at

I’m not too familiar with raycasts so I don’t really know what’s wrong here. I’m creating a raycast from a local script that would point from the camera’s position to another part. The problem is that the raycast would only return a result when the camera is really close to the part.

Could you post your script please?

You’re most likely not setting the proper distance for the raycast.

When raycasting, there’s 2 key elements to keep in mind. Where to start the ray, and where should the ray end.

For example,

local rayorigin = Camera.Position -- Start position of the Raycast.
local raydir = (SomePartName.Position - Camera.Position).Unit -- Get the direction from the camera to the part.
local raydist = 100; -- The length of the ray.
local params = RaycastParams.new() -- Your Raycast parameters.
local rayresult = workspace:Raycast(rayorigin , raydir * raydist, raycastParams)

The distance is for you to determine. The bigger the number, the further the ray goes and the more processing time it takes.

2 Likes
local playercam = game.Workspace.CurrentCamera    

local runservice = game:GetService("RunService")
    runservice.RenderStepped:Connect(function()
    	local params= RaycastParams.new()
    	params.FilterDescendantsInstances = game:GetService("Players").LocalPlayer.Character:GetDescendants()
    	local  unitraything =playercam:ScreenPointToRay(playercam.ViewportSize.X/2, playercam.ViewportSize.Y/2)
    	local  ray = workspace:Raycast(unitraything.Origin,TargetBlock.Position,params)
    	if ray then
    		print(ray.Instance)
    	end 
end)

This is all parented to a localscript. I do see the print(ray.Instance) thing fire every now and then, but it’s only when I’m up close.