Problem with mouse.UnitRay

Currently I’m trying to cast rays base on mouse.UnitRay.

mouseOrigin = mouse.UnitRay.Origin
mouseDir = mouse.UnitRay.Direction
mouseHitP = mouse.Hit.p
rayUltimateGoalCF = CFrame.new(mouseOrigin + mouseDir * Range)

And this is how I cast ray, where RNGOffset is a random accuracy and 10 is the raycasted distance.

rayEndCF = CFrame.new(rayInitialCF.Position + (mouseDir * 1), mouseHitP)
local ray = Ray.new(rayEndCF.p, RNGOffset * 10)

However, the result offsets. From the GIF, when I shoot somewhere nearby, the bullet doesn’t go where my mouse points at. However when I shoot somewhere far away, it works as expected. I’m not sure is it related to raycasting or not, but I think the problem is based on rayEndCF. I’m also concern about what’s the difference and usage between the raycast * 10 and mouseDir * 1?

I also loop cast the ray and uptate rayInitialCF until a target is hit or it’s out of range. Before the first ray is casted, the rayInitialCF is either the camera or HumanoidRootPart, depends on player is in First Person or not.

https://gyazo.com/bacd1ac5c65405432696dcba47b52bd4

I am not sure but I think it might have to do with mouseDir, when in thirst person, based on what you have above, mouseDir is the direction of the ray from your camera to the mouse.Hit, try changing it so that the mouseDir is the direction from tip of gun to mouse.Hit

tip = Vector3
hit = mouse.Hit

mouseDir = (hit - tip).unit

(i have no idea if this would change anything, I am going to be getting off after positing this, sorry if I don’t respond)

edit: by tip of the gun, I mean wherever the first ray starts

I think it actually fixes! Whenever I cast the ray from camera, which rayInitialCF is the Camera CFrame, it works perfectly.

What does this mean?