Raycast being in accurate

I’m trying to make a basic fps gun. To see if a “bullet” hits, I use raycasting. The Ray itself is cast from the camera

The issue is, it’s inaccurate. Based on where I’m looking it, it’ll either go far to the left or right, as well as up.

https://gyazo.com/3457e595f7f3fe903f65a00b417bece7

Part of the code handling making the ray and checking if it god hit :

local stop = false
	
	
BulletRay = Ray.new(CameraCFrame.Position, (CameraCFrame * CFrame.new(0,0,-RayDistance)).Position)
Part,Position = workspace:FindPartOnRayWithIgnoreList(BulletRay,{player.Character})

if Part ~= nil and Part.Parent:FindFirstChild("Humanoid")  then
	stop = true
		
elseif Part ~= nil and Part.Parent.Parent:FindFirstChild("Humanoid") then
	Part = Part.Parent.Parent.Head
	stop = true
		
end

If you want to see the sight of pointing you would need to make it if you right click or press a key that it zooms the gun in so your character shows the point of sight.

the problem is probably with the CameraCFrame variable - make sure you define it right before you make the BulletRay variable.

CameraCFrame is defined right before it, so I doubt that’s the issue

https://gyazo.com/6d0317861b1c55c50f741ed4e0ad38e2

I don’t think you can use the Camera’s CFrame to do the ray casting like that instead you need to either use the ScreenPointToRay or ViewportPointToRay, the only difference being the latter not accounting for gui inset. This is how you would use it:

local Mouse = player:GetMouse()
BulletRay = Camera:ScreenPointToRay(Mouse.X, Mouse.Y, RayDistance)
1 Like

It works, so you’re doing it wrong - sorry. Please show us how you’re implementing it, because that is the issue. Let’s solve the problem by seeing exactly what you’re doing. The previous answers are correct because your ray’s properties are wrong. We need to see how you’re getting them.

Ray casting is very simple so you might be doing something wrong and it does work I just finished making a gun, and that’s what I used.