Home > Mobile >  How to rotate character to the opposite direction smooth slowly?
How to rotate character to the opposite direction smooth slowly?

Time:06-08

private void Update()
{
Quaternion newRotation = Quaternion.AngleAxis(180, Vector3.up);
                transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, .05f);
}

The problem it's not always should rotating by 180. I control the character movement and rotation and at some point i want the character to rotate to the opposite direction no matter what direction he is facing now.

If Y on the rotation is 120 or 45 or 4 or 23 always rotate to the opposite direction.

CodePudding user response:

To solve this problem you need an IEnumerator that maintains the original angle and changes it over time, keep in mind that Point to point changes can never be defined directly in Update or you will have to use a hypothetical variable in Consider the body of the class, which is not recommended.

public IEnumerator DoRotate(float time)
{
    var newRotation = Quaternion.AngleAxis(180, Vector3.up) * transform.rotation;
    
    var progress = 0f;

    while (progress < 1)
    {
        progress  = Time.deltaTime/time;

        transform.rotation = Quaternion.Slerp(transform.rotation, newRotation, progress);

        yield return new WaitForEndOfFrame();
    }
}

After defining IEnumerator, it is enough to start it only once, where it is needed, as below, and the character will rotate at the defined time.

public void Start() => StartCoroutine(DoRotate(2f)); // rotate over 2 seconds
  • Related