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. Dismiss Notice

Keeping Rotation From Last Position

Discussion in 'Scripting' started by Simplified, Jun 7, 2016.

  1. Simplified

    Simplified

    Joined:
    May 28, 2016
    Posts:
    19
    Been at this for a while and can't figure it out. The problem is that when the distance between the two object less than 0.1f, it doesn't keep the last rotation from when it was looking. I have to do this using an "if-else" due to the way my game plays. The rotation just snaps to the default position, and I need it to keep its rotation from the "LookAtMove" method. If I don't, the object slowly rotates over time.

    Code (CSharp):
    1.         if (Vector3.Distance(transform.position, target.position) > 0.1f)
    2.         {
    3.             LookAtMove();
    4.             animate.SetFloat("Running", 0.1f);
    5.             animate.SetFloat("Run_Speed", Speed * 2);
    6.         }
    7.  
    8.         else if (Vector3.Distance(transform.position, target.position) < 0.1f)
    9.         {
    10.             LookAtStill();
    11.             animate.SetFloat("Running", 0.0f);
    12.         }
    13.     }
    14.     void LookAtStill()
    15.  
    16.     {
    17.  
    18.         // I need to get the last rotation value. Deleted what was here after many failed attempts.
    19.        
    20.     }
    21.  
    22.     void LookAtMove()
    23.  
    24.     {
    25.         var newRot = Quaternion.LookRotation(target.position - transform.position, hit.normal);
    26.         transform.rotation = Quaternion.Lerp(transform.rotation, newRot, 50 * Time.deltaTime);
    27.     }
    28.  
     
  2. Errorsatz

    Errorsatz

    Joined:
    Aug 8, 2012
    Posts:
    555
    Would saving it to a field from LookAtMove work?
    Code (csharp):
    1. private Quaternion _lastRotation;
    2.  
    3. void LookAtMove () {
    4.    var newRot = Quaternion.LookRotation(target.position - transform.position, hit.normal);
    5.    _lastRotation = Quaternion.Lerp(transform.rotation, newRot, 50 * Time.deltaTime);
    6.    transform.rotation = _lastRotation;
    7. }
    8.  
    9. void LookAtStill () {
    10.    transform.rotation = _lastRotation;
    11. }
     
    Simplified likes this.
  3. Simplified

    Simplified

    Joined:
    May 28, 2016
    Posts:
    19
    Can't thank you enough, that did the trick. What I was trying to do before was grab the last rotation from LookAtMove doing a different technique(which would make the code much more complicated), but I forgot all about storing it in a global variable defined at the beginning of the script.