Gun leaning in unity

Hello,

I am trying to make a gun lean script so that whenever I click the Q key it leans my player left and it will do the opposite for the E key. But I have a issue where I can only lean into the right directions (left and right) if I am facing a certain direction. So if I am facing a different direction it will lean me forwards and backwards instead of left and right. I have attached my code and a google drive link to my video that contains my issue below just to shot what I mean.

Google Drive: Issue - Google Drive (Copy and paste into browser, you should have access to the folder, it also does not contain any viruses)

Code:

using System.Collections; using System.Collections.Generic; using UnityEngine;

public class GunLean : MonoBehaviour { [SerializeField] private float Amount; [SerializeField] private float LerpTime; [SerializeField] private Quaternion initalRoatation; [SerializeField] private bool IsLeaningLeft; [SerializeField] private bool IsLeaningRight;

private void Awake()
{
initalRoatation = transform.rotation;
}

private void Update()
{
if (Input.GetKey(KeyCode.Q) && !IsLeaningRight)
{
IsLeaningLeft = true;
Quaternion newRot = Quaternion.Euler(transform.localRotation.x, transform.localRotation.y, transform.localRotation.y + Amount);
transform.localRotation = Quaternion.Slerp(transform.localRotation, newRot, Time.deltaTime * LerpTime);
}
else
{
IsLeaningLeft = false;
transform.localRotation = Quaternion.Slerp(transform.localRotation, initalRoatation, Time.deltaTime * LerpTime);
}

  if (Input.GetKey(KeyCode.E) && !IsLeaningLeft)
  {
      IsLeaningRight = true;
      Quaternion newRot = Quaternion.Euler(transform.localRotation.x, transform.localRotation.y, transform.localRotation.y - Amount);
      transform.localRotation = Quaternion.Slerp(transform.localRotation, newRot, Time.deltaTime * LerpTime);
  }
  else
  {
      IsLeaningRight = false;
      transform.localRotation = Quaternion.Slerp(transform.localRotation, initalRoatation, Time.deltaTime * LerpTime);
  }

}
}

I am a little confused, but when am I not? lol… But generally you only want one declaration active at a time, especially in Update(). So to put it in lay-mans terms:

void Update()
{
    GetInputs();
    CharacterUpdatePos();
}
void CharacterUpdatePos()
{
   if (isLeaningLeft) { quaternion = forward/left logic }
   else { if (isLeaningRight) { quaternion = forward/right logic }
   else { quaternion = forward/normal logic }
 }
}
void GetInputs()
{
   if (KeyIsDown.Keycode(Q)) { isLeaningLeft = true; } else { isLeaningLeft = false; }
   if (KeyIsDown.Keycode(E)) { isLeaningRight = true; } else { isLeaningRight = false; }
}

other than that, you might want to Debug.Log or use a Ray to determine actual forward, and make sure your Quaternions are rotating properly. If your rotation isn’t right, it will always lean North and South, or East and West.