RayCast in Third person Shooter

Hi,

Im making a third person shooter and Im using Raycast to detect an hit point and use it to set the destination of the bullet from the muzzle point of the weapon.
The origin of my raycast is the center of the camera.
The problem here is that in case there is an hit point behind the weapon my bullet go backwards so I want to avoid this behaviour.

I upload two pictures and the script to explain myself better :

        distance = Vector3.Distance(player.transform.position, cam.transform.position);
        Vector2 screenCenterPoint = new Vector2(Screen.width / 2f, Screen.height / 2f);
        Ray ray = Camera.main.ScreenPointToRay(screenCenterPoint);
        Debug.DrawRay(ray.origin + cam.transform.forward * distance, ray.direction * 1, Color.yellow);
        Debug.DrawRay(ray.origin, ray.direction * 1, Color.red);
        Debug.DrawLine(cam.transform.position, player.transform.position, Color.blue);

The yellow ray is the forward direction starting from the center of the camera but must begin where the position of the gun is. I use the Vector3.Distance to determine how far should the origin’s ray start but if the camera goes down or up this distance is not accurate.(Picture2)

The red ray has has the camera position as origin but it will detect objects that are behind.

The blue ray is just a draw Line debug.

In other words I want that my yellow ray starts at the end of the blue ray always
How can I achieve this? I hope I make myself clear and I hope u can help me.
Thank you

Hmm I’m not sure I understand your question but you can place a Game Object at the end of the gun, use that as the Ray starting point and the center of the screen as the final point.

You can also do a Raycast from the Camera to the Gun to see if the gun is past a wall and if so don’t shoot.

I made a Third Person Shooter Controller here Awesome Third Person Shooter Controller! - Code Monkey

Hi CodeMonkey ! I wanna say thank you for your time to reply me and thank you for your great work sharing tutorials. I’m one of your subscriber on you tube and I actually use your third person shooter video as a starter point.
My solution was not so elegant but it works as I wanted.
As you said I have placed a game object with a is trigger collider at the end of my muzzle point and with a specific layer mask. Then I shoot a ray from the camera to that game object and use the hit point to shoot another ray which hit point will give me the destination of my bullet should go .
Now everything is in between player and camera won’t be considered as a bullet target and I don’t have bullets going backward