FPS recoil

I’m trying to add recoil to my fps game. The cross hair and gun are parented to the camera so I thought that I could just rotate the camera slightly up every time the player fired. But for some reason, the camera rotates up for a split second and then snaps back to where it was, which I definitely don’t want. The first script I have on my camera and the other on my gun .Thanks.

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class MouseLook : MonoBehaviour
{

public float mouseSensitivity = 100f;

public Transform playerBody;

private float xRotation = 0f;

// Start is called before the first frame update
void Start()
{
    Cursor.lockState = CursorLockMode.Locked;
}

// Update is called once per frame
void Update()
{
    float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
    float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

    playerBody.Rotate(Vector3.up * mouseX);

    xRotation -= mouseY;
    transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
    xRotation = Mathf.Clamp(xRotation, -90f, 90f);

    if (Input.GetButtonDown("Fire1"))
    {
        transform.Rotate(Vector3.left, 20f);
    }
}

}

using UnityEngine;

public class Gun : MonoBehaviour
{

public float damage = 10f;

public float range = 100f;

public Camera fpsCam;

public ParticleSystem muzzleFlash; 

void Update()
{
    if (Input.GetButtonDown("Fire1"))
    {
        Shoot();
    }
}

void Shoot()
{
    muzzleFlash.Play();

    RaycastHit hit;
    if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
    {
        Debug.Log(hit.transform.name);
    }
}

}

I’m writing this from my phone so can’t test this theory but it looks like that might happen because you’re not updating your xRotation. This means that you rotate up 20 degrees and that is shown in the split second before the next frame when you set the rotation back to being your previous xRotation (minus mouse movement).

If this is the case then either adjusting your xRotation when you set the recoil rotation OR at the start of the frame getting a fresh xRotation from your transform will solve your issue.

Let me know how it goes!