# Trouble Rotating an object

I’m attempting to rotate a GameObject for a sprite, so that it can have a minimum of -90 degrees and a maximum of 90 degrees (for a 2D game, so this is the z axis I am rotating). I do not have too much experience with unity, so the only thing I could think of to try was:

transform.rotation.z = newRotation; where newRotation would be a float for the number of degrees.

This produced an error, so I learned that it cant be assigned like transform.position.

I then looked into the docs and tried using transform.rotate
Being that I only want it to rotate from -90 → 90, my code looked something like this:

``````using UnityEngine;
using System.Collections;

public class FlightController : MonoBehaviour {

public float rotSpeed = 20f;

void Start () {

}

void Update () {
transform.Rotate(Vector3.forward * rotSpeed*Time.deltaTime);

float newZrot = Mathf.Clamp (transform.eulerAngles.z, -90f, 90f);
transform.eulerAngles = new Vector3 (0f, 0f, newZrot);

if(Input.GetKeyDown(KeyCode.Space)) {
rotSpeed = rotSpeed * -1f;
}

}
}
``````

However this does not work because instead of going into the negatives, it immediately jumps to 360 degrees. My question is simply does anyone have another idea for a way to code this, or is there a way to allow the degrees to be negative?

In typical C# fashion, Vector3 is a struct and should not be mutated. Unity restricts your ability to mutate transform vectors because of this. Instead, you can create a new Vector3, change its values, and assign it to rotation or position.

``````transform.rotation.z = newRotation;
``````

commit to the following idea, as you would with position:

``````Vector3 newRotation = transform.rotation;
newRotation.z = newRotationZ;
transform.rotation = newRotation;
``````

Position in unity is the same way, in order to change a single axis of position, you have to do something like this:

``````Vector3 newPosition = transform.position;
newPosition.x = newPositionX;
transform.position = newPosition;
``````

otherwise Unity will throw a fit.

Also, Unity automatically does some calculations to ensure that rotation remains within the 0 >= x >= 360 angle range. If you’re doing something like rotating over or s/lerping between 0 and 360, you’ll have to do some extra maths.

make a min, max class with unity :-

`````` transform.rotation =  mathf.Clamp(transform.eulerAngles.z, float min = -90f, float max = 90f)
if (value < min)
value = min;
if (value > max)
value = max;
return value;
``````

this way, when the value is bigger than 90 it eqal it to the max value (90) and if it’s smaller than -90 it eqals it to the min value that is (-90)

I hope that will help