[I saw few similar question on stackexchange but none is solving the purpose.]
I want to rotate a 3D object by 90 degrees on different axis on respective inputs. For example if 'a' is pressed, the object should rotate left by 90 degrees. transform.Rotate(0,90,0);
is working but it is not rotating the object smoothly.
I am new to C# and js so cannot manually code but I tried the codes given in this answer at Rotate an object smoothly on the Y axis in Unity. The below code works but it it has two problems - code:
void Update () {
SwingOpen();
}
void SwingOpen()
{
Quaternion newRotation = Quaternion.AngleAxis(90, Vector3.up);
transform.rotation= Quaternion.Slerp(transform.rotation, newRotation, .05f);
}
Problem 1: The above code rotates object without any keyboard inputs.
I added the condition if (Input.GetKeyDown (KeyCode.RightArrow))
but now the object rotates partially on every keyboard input. I want to rotate it by 90 degrees on a single key press.
Problem 2: It will never actually rotate the object by 90 deg. It will always be tending towards 90 deg. I want exact 90 deg rotation to allow multiple 90 deg rotations for 'n' number if inputs.
How can I solve this? Please help. Please let me know if the question isn't clear enough.
[EDIT]
I applied the below script but it is giving me some totally unexpected output
Code:
public float speed = 1;
private int xtimesHit = 0;
private int ytimesHit = 0;
private int ztimesHit = 0;
void Update () {
if( Input.GetKeyDown( KeyCode.RightArrow ) ){
ztimesHit--;
}
if( Input.GetKeyDown( KeyCode.LeftArrow ) ){
ztimesHit++;
}
if( Input.GetKeyDown( "a" ) ){
ytimesHit++;
}
if( Input.GetKeyDown( "d" ) ){
ytimesHit--;
}
if( Input.GetKeyDown( "w" ) ){
xtimesHit++;
}
if( Input.GetKeyDown( "s") ){
xtimesHit--;
}
this.transform.rotation = Quaternion.Lerp(this.transform.rotation, Quaternion.Euler(xtimesHit*90,ytimesHit*90,ztimesHit*90), Time.deltaTime*speed);
}
On running this script If I press rightarrow once followed by 's' the object rotates on 'z' axis and 'x' axis correctly but there after if I press arrowkeys or 'a/s' in both the cases the object rotates on y axis. I dont understand why this is happening.
I want it to rotate w.r.t. the world axis always.