Hi, I'm having a very simple problem when rotating an object. I have a physical control switch that I want to be turned 180 degrees on a key press, then back again anti-clockwise 180 degrees on another key press. The problem im having is limiting the rotation. Using the following code the object will rotate to 180 degrees and stop, but when rotating back to the start position it wont stop, it continues to rotate in the anti-clockwise direction. Code (csharp): static var thePos = new Array();//hold the position of the control thePos[0] = 0; static var turnKnobDirection1:boolean = false; static var turnKnobDirection2:boolean = false; function Update (){ if(turnKnobDirection1 == true){ if(transform.localEulerAngles.z < 180){ transform.Rotate(0,0,100 * Time.deltaTime);//TURN CLOCKWISE } } if(turnKnobDirection2 == true){ if(transform.localEulerAngles.z > 0){//WONT STOP AT 0 DEGREES transform.Rotate(0,0,-100 * Time.deltaTime);//TURN ANTI-CLOCKWISE } } if(Input.GetKeyDown(KeyCode.D)){ if(thePos[0] == 0){//TURN CLOCKWISE turnKnobDirection1 = true; turnKnobDirection2 = false; thePos[0] = 1; }else if(thePos[0] == 1){//TURN ANTI-CLOCKWISE turnKnobDirection1 = false; turnKnobDirection2 = true; thePos[0] = 0; } } } It seems to miss the start rotation of 0 degrees and then continue to rotate back from 360 degrees and round again to 0 degrees. Can anyone help me please? Its driving me crazy! Thanks
I'm not sure there is a 0 degrees, because you can't have both 360 and 0, so it might use 360, perhaps try >1, or .1, or .001.
That's because Euler angles usually never go negative and you are checking for greater than zero. In 99.9% of the time you check EulerAngle it will be between 0.000001 and 359.999999 So you only really need to check in the angle is less than 180 in both directions. Code (csharp): static var thePos = new Array();//hold the position of the control thePos[0] = 0; static var turnKnobDirection1:boolean = false; static var turnKnobDirection2:boolean = false; function Update (){ if(transform.localEulerAngles.z < 180){ if(turnKnobDirection1 == true){ transform.Rotate(0,0,100 * Time.deltaTime);//TURN CLOCKWISE } if(turnKnobDirection2 == true){ transform.Rotate(0,0,-100 * Time.deltaTime);//TURN ANTI-CLOCKWISE } } if(Input.GetKeyDown(KeyCode.D)){ if(thePos[0] == 0){//TURN CLOCKWISE turnKnobDirection1 = true; turnKnobDirection2 = false; thePos[0] = 1; }else if(thePos[0] == 1){//TURN ANTI-CLOCKWISE turnKnobDirection1 = false; turnKnobDirection2 = true; thePos[0] = 0; } } }