Shooter FPS 3d UNITY

Viewed 197

I have a problem with the position of the camera and weapon shot. If you check the photo, on the left is a red ray that is the real direction of the shot. But my weapon is not at the same position of the camera. When I apply the direction to shot, I have this issue and the yellow LineRender (right of the picture) hit the cube.

This problem is only occurs when the shot doesn't hit a gameObject

The black quad of screen is a Canvas to simulate the crosshair Picture

Full Code


void Update() {
    line.SetPosition(0, posGun.position);
    Vector3 auxPos_ = cam.position + cam.forward * distance;
       
      
    if(Physics.Raycast(cam.position, cam.forward, out hit, Mathf.Infinity))
    {
        line.SetPosition(1, hit.point);
    }
    else
    {
        line.SetPosition(1, auxPos_);![alt text][2]
    }
 
    Ray ray = Camera.main.ScreenPointToRay(new Vector3(Camera.main.pixelWidth/2f,Camera.main.pixelHeight/2f, 0));
    Debug.DrawRay(ray.origin, Camera.main.transform.forward * 10, Color.red);
}
1 Answers

Don't simply set the line to where the aiming raycast hits. First, do a 2nd raycast from the gun to where the aiming raycast hits. Then, if that hits anything, draw the line from the gun to that point instead.

void Update() {
    line.SetPosition(0, posGun.position);
    Vector3 auxPos_ = cam.position + cam.forward * distance;
       
      
    if(Physics.Raycast(cam.position, cam.forward, out hit, Mathf.Infinity))
    {
        Vector3 fireDirection = hit - posGun.position;
        Vector3 hitFromGun;
        if (Physics.Raycast(posGun.position, fireDirection, out hitFromGun, Mathf.Infinity))
        {
            line.SetPosition(1, hitFromGun.point);
        }
        else 
        {
            line.SetPosition(1, hit.point);
        }
    }
    else
    {
        line.SetPosition(1, auxPos_);![alt text][2]
    }
 
    Ray ray = Camera.main.ScreenPointToRay(new Vector3(Camera.main.pixelWidth/2f,Camera.main.pixelHeight/2f, 0));
    Debug.DrawRay(ray.origin, Camera.main.transform.forward * 10, Color.red);
}
Related