# Question Rotating Specific Amount In The Correct Direction on Key Press

Discussion in 'Scripting' started by DoubleUU, Mar 5, 2023.

1. ### DoubleUU

Joined:
Dec 29, 2018
Posts:
33
So I've been trying to figure this out most of the day. I've searched a ton of forum posts and read several tutorials but none of the techniques I've tried works the way I'd like.

I have a 3D sidescrolling style game. I would like to have the player object rotate based on a key press from facing left (Y = 0) to facing right (Y = 180). When going from 0 to 180 it should rotate clockwise and when going from 180 to 0, counterclockwise.

That last bit is where I keep getting stuck. All solutions I've tried with Mathf and MoveTowardsAngle, LerpAngle, etc., always rotate clockwise. I have not been able to find any example code rotating an object both ways a specific amount and stopping.

Any help or points to articles would be greatly appreciated. Feeling pretty stuck and out of terms to Google.

2. ### DoubleUU

Joined:
Dec 29, 2018
Posts:
33
Solved my own problem, I think.

Just needed to NOT use the angle versions of those. This is what I ended up with, just in case someone else might find it useful.
Code (CSharp):
1.
2. if (rotating) {
3.
4.     float nextAngleY = Mathf.MoveTowards(transform.eulerAngles.y, targetAngleY, rotationSpeed * Time.deltaTime);
5.     transform.eulerAngles = new Vector3(transform.eulerAngles.x, nextAngleY, transform.eulerAngles.z);
6.
7.     if (transform.eulerAngles.y == targetAngleY) {
8.         rotating = false;
9.     }
10. }

3. ### Kurt-Dekker

Joined:
Mar 16, 2013
Posts:
37,150
You're potentially going to have problems comparing floating point. Here's why:

Floating (float) point imprecision:

Never test floating point (float) quantities for equality / inequality. Here's why:

https://starmanta.gitbooks.io/unitytipsredux/content/floating-point.html

"Think of [floating point] as JPEG of numbers." - orionsyndrome on the Unity3D Forums

I always use this pattern:

Smoothing movement between any two particular values:

You have currentQuantity and desiredQuantity.
- only set desiredQuantity
- the code always moves currentQuantity towards desiredQuantity
- read currentQuantity for the smoothed value

Works for floats, Vectors, Colors, Quaternions, anything continuous or lerp-able.

``desiredVisualsFacing``