Keeping Rotation From Last Position

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.

        if (Vector3.Distance(transform.position, target.position) > 0.1f)
        {
            LookAtMove();
            animate.SetFloat("Running", 0.1f);
            animate.SetFloat("Run_Speed", Speed * 2);
        }

        else if (Vector3.Distance(transform.position, target.position) < 0.1f)
        {
            LookAtStill();
            animate.SetFloat("Running", 0.0f);
        }
    }
    void LookAtStill()

    {

        // I need to get the last rotation value. Deleted what was here after many failed attempts.
       
    }

    void LookAtMove()

    {
        var newRot = Quaternion.LookRotation(target.position - transform.position, hit.normal);
        transform.rotation = Quaternion.Lerp(transform.rotation, newRot, 50 * Time.deltaTime);
    }

Would saving it to a field from LookAtMove work?

private Quaternion _lastRotation;

void LookAtMove () {
   var newRot = Quaternion.LookRotation(target.position - transform.position, hit.normal);
   _lastRotation = Quaternion.Lerp(transform.rotation, newRot, 50 * Time.deltaTime);
   transform.rotation = _lastRotation;
}

void LookAtStill () {
   transform.rotation = _lastRotation;
}
1 Like

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.