Raycasting Issue(Not Accurate)

Hi everyone! I am having a little bit of difficulty with a raycast I set up. It is not very accurate as I show in the video. Any help?

local muzzle =  Camera.Template.Handle.Muzzle
local ray = Ray.new(muzzle.CFrame.p, (Mouse.Hit.p-muzzle.CFrame.p).unit * 999)
local part, pos = game.Workspace:FindPartOnRayWithIgnoreList(ray,{Camera,player.Character,game.Workspace.Ignore})
local damage = 0
				
if part then
	if part.Parent:FindFirstChild("Humanoid") then
		if part.Name == "Head" then
			damage = HeadShot
		else
			damage = BodyShot				
		end
	end
end
1 Like

You should cast the ray directly from the camera forward instead of the muzzle because the muzzle is pointed slightly to the top left which will make it fire off-center.

local camera = workspace.CurrentCamera

local raycastParams = RaycastParams.new()
raycastParams.FilterDescendantsInstances = {character}
raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
local origin = camera.CFrame.Position
local direction = camera.CFrame.LookVector * 256
local raycastResult = workspace:Raycast(origin, direction, raycastParams)

if raycastResult then
	local humanoid = raycastResult.Instance.Parent:FindFirstChild("Humanoid")
	
	if humanoid then
		damage = raycastResult.Instance.Name == "Head" and HeadShot or BodyShot
	end
end
2 Likes

How would I know when it hits something like a part?

If raycastResult is nil, then it did not hit a part. If you want to check if the part is a character, then just do what you did with raycastResult.Instance.Parent:FindFirstChild("Humanoid")

Also I updated the script a little if you want to look it over again.

Ok thank you! And finally how do I get the position of where the raycast hit?

Use raycastResult.Position. You can see what a raycastResult returns here: RaycastResult | Roblox Creator Documentation

I just wanted to point out, workspace:FindPartOnRayWithIgnoreList() is deprecated. Use WorldRoot:Raycast() instead.

I forgot but don’t use the Camera’s forward direction. Use the mouse direction instead because the script won’t work if you were in 3rd person (zoomed out).

local Players = game:GetService("Players")

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

local raycastParams = RaycastParams.new()
raycastParams.FilterDescendantsInstances = {character}
raycastParams.FilterType = Enum.RaycastFilterType.Blacklist
local origin = camera.CFrame.Position
local direction = (mouse.CFrame.Position - origin).Unit * 256
local raycastResult = workspace:Raycast(origin, direction, raycastParams)

if raycastResult then
	local humanoid = raycastResult.Instance.Parent:FindFirstChild("Humanoid")
	
	if humanoid then
		damage = raycastResult.Instance.Name == "Head" and HeadShot or BodyShot
	end
end

It won’t be in 3rd person. But thank you for the suggestions