Raycasting wont work (camera to mouse position)

Im trying to make a raycast from a part at the cameras position to the mouse position, It does not work and I cant figure out why.

local raycaster = Instance.new("Part")
raycaster.CFrame = camcframe  --from workspace.currentcamera
raycaster.CFrame = CFrame.lookAt(raycaster.Position, mousepos) --mouse.hit
local raycast = workspace:Raycast(raycaster.Position, raycaster.Orientation)
print(raycast.Instance)

returns "attempt to index nil with ‘Instance’ "

code is exactly the same in script but triggered by a remotevent

1 Like

the second parameter to Raycast is a vector3 which should represent the direction you want the ray to travel in as a vector. Orientation returns the XYZ angles in degrees of the part, rather than its look direction
try this instead:

local mouse = game.Players.LocalPlayer:GetMouse()
local raycast = workspace:Raycast(workspace.CurrentCamera.CFrame.Position, (mouse.Hit.Position-workspace.CurrentCamera.CFrame.Position)*10)
print(raycast.Instance)
1 Like

that fixed it!! also, why there is a *10 at the end of the second parameter?

I just do that to add leniency to the raycast, because the second parameter uses the size of the vector to determine how far the raycast should reach, so if the raycast travels the exact distance there is a chance that it wont detect the part
it would probably still work without the *10

1 Like

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