Rotating on a button press not working quite right

Hi there, Im new to Unity and scripting as well. Im just trying to start off with making a simple script that will start rotating a cube on a button press, go 90 degrees then stop. I have it sort of working, but I do have a couple problems with it.

Currently my script will rotate a small amount every time I hit space bar rather than just rotating the full 90 degrees all at once. I have to press space bar over and over again (about 30 times) before it reaches 90 degrees. Also, it never actually stops directly on 90 degrees, it usually ends up going a degree or two past 90 before stopping, since the last time I press space bar it will be at around 89 egrees, then the last press will send it little beyond 90.

Heres the Code:

var rotateSpeed = 200;


function Update () {
	
		if (Input.GetButtonUp ("Jump")){
				
			if(transform.eulerAngles.z <= 90){
				transform.Rotate(Vector3(0, 0, 1) * Time.deltaTime * rotateSpeed);
			}
		}
	}

Im assuming there must be something simple that have missed. Can anyone give a simple artist a hand?

Try something like this:

var rotateSpeed = 10; 
private var RotatingMyCube = false;

function Update()
{
 if (Input.GetButtonUp ("Jump"))
    RotatingMyCube = true;

 if(transform.eulerAngles.z <= 90  RotatingMyCube == true){
            transform.Rotate(Vector3(0, 0, rotateSpeed)); 
}
else
RotatingMyCube = false;
}

That should give you a 90 degree rotate and 90 degrees only.

Remember that update gets called EVERY SINGLE FRAME. So it’s essentially one giant While loop. (And… well do something stupid like what I did by adding a while loop in an update function, you’ll crash Unity XP) So you need to do an if-then statement, and turn a boolean on and off to get the effect you want.

Here is what your code says in English:

If you press the jump button, and its number for Z in the Transorm Inpector is less than 90, then you will rotate around the object’s Z axis by an amount of degrees equal to rotateSpeed multiplied by the time it took the last frame to occur.

That’s not what you said you want. :wink:

Here’s a solution. Let me know if there’s something about it you don’t understand. I also don’t know exactly what you’re doing; with this code, you can rotate again and again, but each time it will rotate exactly 90 degrees in Z. I can take that out if you don’t want that.

var rotateSpeed : float; 

private var rotating;

function Update () 
{ 
	if (!rotating  Input.GetButtonUp("Jump")) Rotate();
}

function Rotate ()
{
	rotating = true;
	var zRotation = 0F;
	while (rotating)
	{
		var deltaDegrees = rotateSpeed * Time.deltaTime;
		if (zRotation >= 90 - deltaDegrees)
		{
			deltaDegrees = 90 - zRotation;
			rotating = false;
		}
		else zRotation += deltaDegrees;
		
		transform.Rotate(Vector3(0, 0, deltaDegrees));
		yield;
	}
}

What Teriki Tora won’t work. (Please test code before posting. :wink:) It’s not framerate-independent and it doesn’t stop at 90 degrees. Petey’s solution is better but it’s not precise either. (The lower the framerate, the more error is introduced for their solutions.) Technically my solution isn’t exact either, but it’s only off by floating point error, which is negligible.

371499–12870–$rotatejump_151.js (463 Bytes)

You could run the turn as a function outside of the update function, see if this does it.

var rotateSpeed = 200; 

function Update () { 
    if (Input.GetKeyUp ("9")) {//Press 9 to test
    Turn90();
    }
}

function turn90(){
    while(transform.eulerAngles.z <=90){
        transform.Rotate(vector3(0,0,1)*Time.deltaTime * rotateSpeed);
        yield;
        }
}

This is untested ( not around unity right now ) but I think it’ll work.

Edit - haha, looks like by the time I typed this out you’ve got a whole bunch of other solutions :slight_smile:

1 Like

Thanks for the responses! What Jesse has goin is closer to what I want I think. I do want to be able to rotate as many times as you want. Ultimately I want to be able to rotate it back and forth, but Im assuming the backwards rotation will be the same thing with some negative numbers and just attached to another key press.

I m however very confused by most of what is going on in here :expressionless:

var rotateSpeed : float;  // Im assuming this just means you are creating a variable with no default value? So the user creates the value in the inspector?

private var rotating;  //what does this variable equal? It is being used as a boolean, but its not defined as false?

function Update () 
{ 
	if (!rotating  Input.GetButtonUp("Jump")) Rotate();
}

function Rotate ()
{
	rotating = true;
	var zRotation = 0F; //Im assuming the "0F" here is just a typo and it should just be "0"
	while (rotating)
	{
		var deltaDegrees = rotateSpeed * Time.deltaTime;
		if (zRotation >= 90 - deltaDegrees) 
//Im not sure I understand all this subtraction business. I thought I would want to add up numbers until reaching 90. How does this work?
		{
			deltaDegrees = 90 - zRotation;
			rotating = false;
		}
		else zRotation += deltaDegrees; //is this adding 1 to delta degrees every frame?
		
		transform.Rotate(Vector3(0, 0, deltaDegrees));
		yield; //I couldnt find anything on this command in the scripting api
	}
}

One thing I noticed is that the slower I set the speed on the rotation, the further past 90 degrees this rotates. If rotateSpeed is set under a hundred, i rotates over 200 degress. The faster I set it, it will stop closer to 90, but still never anywhere within .01 of 90 degrees…

var rotateSpeed : float;	//Im assuming this just means you are creating a variable with no default value? So the user creates the value in the inspector?

Yep. I never use default values for Inspector-editable variables. It’s just code clutter to me. Plus, as you had it, you couldn’t add decimal places, because “= 200” made it into an int.

private var rotating;  //what does this variable equal? It is being used as a boolean, but its not defined as false?

Booleans are false by default. You can explicitly use “= false” if you want.

var zRotation = 0F; //Im assuming the "0F" here is just a typo and it should just be "0"

Not at all. It makes it a float instead of an int.*

var deltaDegrees = rotateSpeed * Time.deltaTime;
if (zRotation >= 90 - deltaDegrees)	//Im not sure I understand all this subtraction business. I thought I would want to add up numbers until reaching 90. How does this work?
{
	deltaDegrees = 90 - zRotation;
	rotating = false;
}
else zRotation += deltaDegrees; //is this adding 1 to delta degrees every frame?

transform.Rotate(Vector3(0, 0, deltaDegrees));

zRotation gets deltaDegrees added to it every frame (not 1, like you asked) until it’s close to 90 degrees. However, for the final rotation before stopping, adding rotateSpeed * Time.deltaTime would be rotating past 90 degrees. Therefore, we alter deltaDegrees to be exactly the amount we need (90 - zRotation).

yield; //I couldnt find anything on this command in the scripting api

It waits a frame.
http://unity3d.com/support/documentation/ScriptReference/index.Coroutines_26_Yield.html

*I’m assuming you deleted the F from the code and then saved. :wink:
Let’s examine what happens then:

var deltaDegrees = rotateSpeed * Time.deltaTime;
zRotation += deltaDegrees;

When you add fractional values to an int, the digits after the decimal place get truncated. zRotation won’t line up with the rotation of the cube, because deltaDegrees is a float. The smaller rotateSpeed is, the more error is introduced, because the fractional values are a greater percentage of the overall rotation per frame. You’ll always be rotating for too much time, though, regardless of the actual error.

Time.deltaTime is a small value. If rotateSpeed is small, then deltaDegrees is going to be small. If deltaDegrees is smaller than 1, every frame, then zRotation will always be zero, and the rotating will never end!

I don’t have pre-Unity 3 around me, and I don’t recall using F back when I used UnityScript regularly. If F gave you a compiler error, then either get the Unity 3 beta or use 0.0 instead of 0F.

Ahh yes, this was the problem. I dont have Unity3, so setting it to 0.0 did the trick.
Im still trying to wrap my brain around the while loop, but I will get it eventually.
Thank you!

While you’re thinking about the while loop, here’s my compound solution :):

https://www.karmavore.ca/shop_item.php?pcatid=10&id=1149
I get it here but I don’t have a local store that sells it.