Best way to fire from object in an overlay first person camera?

I’m currently using an overlay camera to present the player POV. However theres an issue with getting the right position for the spawn origin and direction. Here’s my attempt which unfortunately not only requires extremely low values i.e. .0002f but has wonky scaling. The reason I’m using an overlay FPS camera is to keep the angles consistent

    private void Shoot()
    {
        Ray ray = new Ray(_camera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 0.0f)), _camera.transform.forward);
        if (Physics.Raycast(ray, out RaycastHit hit))
        {
            Rigidbody projectilePrefab = Instantiate(_projectilePrefab, _camera.transform.position + _shotOffset, Quaternion.identity);
            StartCoroutine(Move(projectilePrefab, hit.point - _camera.transform.position, _speed));
        }
        else
        {
            Rigidbody projectilePrefab = Instantiate(_projectilePrefab, _camera.transform.position + _shotOffset, Quaternion.identity);
            StartCoroutine(Move(projectilePrefab, ray.direction, _speed));
        }
        //Vector3 moveDirection = _shotOriginPos
    }

Looking at line 3… are you aware of this method?

The next question would be to why line 6 instantiates the bullet in one place but line 7 moves it from a different point. EDIT: never mind, perhaps I’m not reading your Move() method correctly… either way though… long lines of code! Break 'em out so you can debug them.

This is the hazard of long hairy nasty lines of code. :slight_smile:

If you have more than one or two dots (.) in a single statement, you’re just being mean to yourself.

Putting it all one one line DOES NOT make it faster. That’s not how compiled code works.

How to break down hairy lines of code:

http://plbm.com/?p=248

Break it up, practice social distancing in your code, one thing per line please.

“Programming is hard enough without making it harder for ourselves.” - angrypenguin on Unity3D forums

“Combining a bunch of stuff into one line always feels satisfying, but it’s always a PITA to debug.” - StarManta on the Unity3D forums

I tried it and it doesn’t seem to work. However, I downloaded the FPS project and setup my camera exactly as how they did it and its working properly now. Basically just place the overlay camera as a child of the main camera.

1 Like