Limited Rotation in a 2D Platformer

Okay so I am a complete and utter newbie in coding, so please feel free to talk to me like I’m a child and if you could explain or post references to any functions you use I would greatly appreciate it.

I am currently trying to make my first game using Unity, it is gonna be a classic 2D platformer, my character has a rather wide base so one of the things I want to be able to do, to avoid being stuck on solid horizontal spaces is rotate my character sprite within a limited axis relative to either the ground, or his starting position, whichever would be more efficient. I currently have a Mathf.clamp on him to limit rotation along his Z axis to within 45 but that seems to be based on current position so it helps stop him from rotating too extremely but doesn’t stop it at thresholds.

        private void lockedRotation()
        {
            rotationZ = Mathf.Clamp (rotationZ, -45, 45);

            transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, transform.localEulerAngles.y, -rotationZ);
        }

I would appreciate any help that could be offered on this, and any effort that can be put forward to help me in the future would also be greatly appreciated.

Because you are setting rotationZ each time, then any next time you wanna use it, it will be new value. So I think you need to keep/store your initial rotation value in a variable (like initialRotationZ) and use another variable to keep your calculation for further use.

using UnityEngine;

public class RotationController : MonoBehaviour {
	float initialRotationZ;

	void Start()
	{
		initialRotationZ = transform.rotation.z;
	}

	void lockedRotation()
	{
		float rotationZ = Mathf.Clamp (initialRotationZ, -45, 45);

		transform.localEulerAngles = new Vector3(transform.localEulerAngles.x, transform.localEulerAngles.y, -rotationZ);
	}
}