Lean main camera depending on input Axis (Horizontal)

I’m trying to do a simple leaning function for my character. Is an FPS game, what I’m trying to achieve is a small leaning of the main camera when moving on the horizontal axis to simulate the head movement beign dragged. The script kinda works but it doesn’t take in account the negative value of the axis iven, so it only lean in one direction.

NOTE: The leaning is achieved by just rotating the main camera z euler angle.

Here is the script:

using UnityEngine;

[AddComponentMenu("Player Scripts/Player Head Track")]
public class PlayerHeadTrack : MonoBehaviour {
	
	public GameObject mainCam;
	
	public float leanAngle = 5f;
	public float leanSpeed = 10f;
	
	float curAngle;
	float targetAngle;
	float angle;
	
	Quaternion rotAngle;

	// Lean main camera when moving horizontally
	public void LeanCamera (float axis) {
		curAngle = mainCam.transform.localEulerAngles.z;
		
		targetAngle = leanAngle - axis;
		
		if ( axis == 0.0f ) targetAngle = 0.0f;
		
		angle = Mathf.Lerp( curAngle, targetAngle, leanSpeed * Time.deltaTime );
		
		rotAngle = Quaternion.Euler( mainCam.transform.localEulerAngles.x, mainCam.transform.localEulerAngles.y, angle );
		mainCam.transform.localRotation = rotAngle;
	
	}
}

To calculate the angle from my player controller script I just call the function LeanCamera this way:

When player is moving

playerHt.LeanCamera(Input.GetAxis("Horizontal"));

When doing nothing

playerHt.LeanCamera(0.0f);

How can I get both positive/negative values of the horizontal axis to work? I know they should be there no matter what, maybe is a problem on the LeanCamera script itself? Thanks in advance.

Hey,

Having read your last comment, I believe I understand what you want now.

Try using Quaternion.Lerp:

float maxRot = 45.0f; //Max neg and pos strafe rotation value
float rate = 2.0f; //Rate of change for Lerp

mainCam.transform.rotation = Quaternion.Lerp(mainCam.transform.rotation, Quaternion.Euler(axis * maxRot, mainCam.transform.rotation.y, mainCam.transform.rotation.z), Time.deltaTime * rate);

Hopefully that should work. Haven’t tested though. :slight_smile:

Klep