Rotate my player gradually without "Jumping"
Hello, i have a rotate script, that works, just that it "jumps" if i just press one time it rotate like 35 degrees and if i just hold it works good, just that i dont know how to make that when pressing one time it rotates a bit, my code:
if (ClockwiseRotation==false){
rotZ += Time.deltaTime * RotationSpeed * -100;
}
else{
rotZ += -Time.deltaTime * RotationSpeed * 100;
}
if (Input.GetKey(KeyCode.LeftArrow)){
transform.rotation = Quaternion.Euler(0,0,rotZ);}
/* i tried by gradually increase a variable but it didnt work */
Answer by Ermiq · Apr 05, 2021 at 08:44 PM
The code inside Update() { ... }
is executed in every frame. With 60 frames per second it's executed every 0.016 sec.
Obviously, you have this code in the Update()
. And rotZ
is getting inreased/decreased in every frame, so every 0.016 sec rotZ
is in(de)creased by 0.016 * 100 * RotationSpeed
.
The code inside if (Input.GetKey(...) { ... }
is executed in every frame only when you hold the LeftArrow
key. So, it does correctly rotate the player because in every frame rotZ
is in(de)creased and right here the player is rotated to the given rotation that didn't change too much yet.
And what happens if you don't hold the key? The rotZ
is getting in(de)creased continuously in every frame. So, to the moment when you finally decide to press the key, the transform.rotation = ...
method receives rotZ
value that is now pretty far from where it was last time the key was pressed, and you get a big 'jump' rotation.
Move the code that in(de)creases rotZ
into the scope that is executed only if you hold the key pressed, so rotZ
will be changed only when it's really needed to change - when you press and hold the LeftArrow.