Fire projectiles in the direction the player is lookin at in Fps Microgame template

I’m modding the FPS Microgame Template project in Unity, which is a First Person Shooter game template available for free at the Unity Asset Store. The gun that comes with this template fires projectiles instead of using raycasts to simulate gunshots.

What I’m trying to do is make the gun look to the object that is directly in front of the player. That is, the gun muzzle should be rotated to face the hitting point of a ray coming from the camera.transform.forward.

I need the gun to point toward the center so the player can always have a precise feedback about where his shots will land. In the future, I will implement recoil simulation and all sorts of things that will influence the precision of the gun. But for that to work, I need it to have a baseline aiming point at, hopefully, the center of the screen.

I’ve tried all manner of things without much success. Currently, my closest solution is:

Vector3 origin = camera.transform.position;
Vector3 direction = camera.transform.forward;
RaycastHit hit;
if (Physics.Raycast(origin, direction, out hit, distance)){
        WeaponParentSocket.transform.LookAt(hit.point);
}

This solution, unfortunately produces a very imprecise result, as you can see from the image below. The white line is the raycast from the camera and the pink line is the direction that the gun is currently pointing at:

How would one achieve the effect I’m looking for?

If the camera.forward and the gun.transform.forward are not precisely on the same single line in space, you cannot solve this except to choose an arbitrary convergence distance.

In real life this is how actual guns fire: the bullet leaves the barrel several inches below your line of sight, generally aligned so that the bullet rises up to your line of sight precisely as it strikes the target.

In video games there are a variety of different approaches. Search up aiming, line of sight, convergence, trajectory, etc.

Thank you for taking the time to answer my question!

I ended up using a different solution.

Instead of aiming the gun directly at the point I want the shot to land, I just shoot a raycast from the center of the camera. Then I save the raycast hit.point to a variable and use it’s coordinates to calculate the direction from the gun muzzle to the point. With these values I can rotate each projectile to face the location which the player intended to shoot.