Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question Rotating Specific Amount In The Correct Direction on Key Press

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

  1. DoubleUU


    Dec 29, 2018
    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


    Dec 29, 2018
    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):
    2. if (rotating) {
    4.     float nextAngleY = Mathf.MoveTowards(transform.eulerAngles.y, targetAngleY, rotationSpeed * Time.deltaTime);
    5.     transform.eulerAngles = new Vector3(transform.eulerAngles.x, nextAngleY, transform.eulerAngles.z);
    7.     if (transform.eulerAngles.y == targetAngleY) {
    8.         rotating = false;
    9.     }
    10. }    
  3. Kurt-Dekker


    Mar 16, 2013
    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:

    "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.

    The code:

    You can see an example of it here in this project:

    Specifically here, around line 99 where I set the
    based on facing:

    and then line 108 where it lerps towards. I prefer the lerp feel, but you could use MoveTowardsAngle instead.