# Character rotation to a specific degree

Hello everyone, I am a making a 3rd person game and in my game I would like the character to -only- be able to change it’s rotation on the y axis to positive and negative 90-180-270-360. My code currently works for rotating my character an additional 90 degrees from what it’s currently at. The problem occurs when I’m interacting with physic objects, it’s not uncommon for my character to rotated 5-10degrees on the y axis while plowing through a bunch of cubes. I’m okay with that but I would like it if every time I changed the rotation of my character it was set specifically to 90degrees and so on rather than my current rotation + 90. Here’s my code (Note the spacing appears to be off but in the code it is correct)

function Update ()

{

if(Input.GetKeyDown(“e”))

{

transform.Rotate(0, 90, 0);

}

if(Input.GetKeyDown(“q”))

{

transform.Rotate(0, -90, 0);

}

}

If you have a rigidbody applied to your object you could check freeze rotation box on the y axis in the rigidbody script. This will only allow y-axis rotation through scripting.

This code isn’t very safe for the very reason you are asking this question… if the rotation get offset a bit, the rotate by ± 90 degrees will be all off.

What you could do is use the the transform.LookAt() function to look in a direction. It points the transforms z vector at the point you give it.

``````function Update (){

if(Input.GetKeyDown("e")){

transform.LookAt(transform.position - transform.right);

}

if(Input.GetKeyDown("q")){

transform.LookAt(transform.position + transform.right);

}

}
``````

You could still run into the same problem with the offset if there is not rigidbody to freeze the y-axis rotation.

What you could do then is check your players current forward vector against world vectors that are constant and rotate using those. This would be the safest if the above rigidbody suggestion doesn’t work.

this is rotesion lick tetris if need if you want something like this

``````#pragma strict

var x : float;
var y : float;
var z : float;

function Update() {

if (Input.GetKeyDown(KeyCode.Q))
{ transform.Rotate(x, y, 90); }
``````