I’ve been working on a third person gun framework, and i’ve run into an issue:
To shoot the gun, i send out a raycast in the direction of the camera and from the position with the camera. This means when you shoot the gun, it will shoot from the crosshair (at least in theory - it actually raycasts slightly above the crosshair, but i’ll get into that later). The thing is, this means it’s not really shooting from the gun, it’s shooting from the camera, so if something is blocking the camera you won’t be able to shoot anything, and if the camera is zoomed out the raycast will be traveling further.
(you can also see for yourself here):
-- this is essentially how i've been raycasting
workspace:Raycast(camera.CFrame.Position, camera.CFrame.LookVector.Unit * 300, ...)
So, my question is this: how can i raycast from the gun while still having the shot line up with the crosshair?
For a third person shooter you should always raycast from the weapon to the mouse.
Though, a few posts down it appears to be a 2nd person (over the shoulder) shooter (correct me if I’m wrong).
You should raycast from the weapon to the mouse again, but since there’s a camera you should raycast from the center of the camera to the viewport instead of the mouse.
It works by getting a vector at the camera.CFrame.Position pointing to the mouse.hit.position and converting it into a unit vector because why not. An alternative would be using the direction property from a ray returned from Camera:ViewportPointToRay()
I enabled the mouse and saw that it was slightly above the crosshair, and it turns out it was because i hadn’t enabled ScreenGui.IgnoreGuiInset, so - after doing that - it works perfectly. Thanks for all your help everyone.