Clamp rotation using Quaternion.Euler does not work

I have an object that I am rotating with swipe movement. I want to clamp rotation at 90 and -90 degrees, but the Quaternion.Euler doesn’t seem to be the correct values og I am missing som info on how the work.

Hope someone can help a newb out :smiley:

Here is my code

public class PlayerScript : MonoBehaviour
{
   float speed = 0.1f;
   Vector3 mPrevPos = Vector3.zero;
   Vector3 mPosDelta = Vector3.zero;



    // Update is called once per frame
    void Update()
    {
        if(Input.GetMouseButton(0))
        {
            mPosDelta = Input.mousePosition - mPrevPos;
            transform.Rotate(0.0f, -mPosDelta.x*speed, 0.0f);
        }
        mPrevPos = Input.mousePosition;
        //Clamp rotation
        float minRotation = -90;
        float maxRotation = 90;
        Vector3 currentRotation = transform.localRotation.eulerAngles;
        currentRotation.y = Mathf.Clamp(currentRotation.y, minRotation, maxRotation);
        transform.localRotation = Quaternion.Euler (currentRotation);
        
    }
    

}

You could use localEulerAngles.y and make currentRotation a float.

float currentRotation = transform.localEulerAngles.y;
currentRotation = Mathf.Clamp(currentRotation, minRotation, maxRotation);
transform.localEulerAngles.y = currentRotation

Also I don’t think eulerAngles is a property of localRotation, but there weren’t any errors or warnings?

Thanks for the response @Magso

Much simpler to make it a float :slight_smile:
I don’t get any errors from transform.localRotation.eulerAngles…But I do get one from your proposed code

transform.localEulerAngles.y = currentRotation;

Blockquote

Cannot modify the return value of ‘Transform.localEulerAngles’ because it is not a variable

Blockquote

lol I got this to work btw

   void Update()
    {
        if(Input.GetMouseButton(0))
        {
            mPosDelta = Input.mousePosition - mPrevPos;
            transform.Rotate(0.0f, -mPosDelta.x*speed, 0.0f);
        }
        
        //Clamp rotation

		// create a new vector 3, "tempAngles" from the current transform.eulerAngles;
		tempAngles = transform.eulerAngles;
		// when the transform.eulerAngles.y is greater than 180...
		while(tempAngles.y > 180)
		{
		    //subtract 360 from transform.eulerAngles.y so it is definitely negative. 
			tempAngles.y -= 360;
		}
		//then create a new float variable for the y angle clamp using the tempAngles above.
		float clampedY = Mathf.Clamp(tempAngles.y, -90, 90);
        
		//then actually perform the new transform. 
		transform.eulerAngles = new Vector3(0f, clampedY, 0f);
	
        
        mPrevPos = Input.mousePosition;
}