rotate towards a certain location upon getKeyDown

Hi. I am making a Character that can rotate 90 degrees upon pressing a key

 void Update()
    {
        if (Input.GetKey(KeyCode.W))
        {
            rotate();
        }
   
    }
    //values that will be set in the Inspector
    public float RotationSpeed;

    //values for internal use
    private Quaternion _lookRotation;
    private Vector3 _direction;
    void rotate()
    {
        //find the vector pointing from our position to the target
        _direction = (Target.position - transform.position).normalized;

        //create the rotation we need to be in to look at the target
        _lookRotation = Quaternion.LookRotation(_direction);

        //rotate us over time according to speed until we are in the required rotation
        transform.rotation = Quaternion.Slerp(transform.rotation, _lookRotation,RotationSpeed);
    }

My idea of the code is that upn pressing the key “w”, the character will smoothly rotate towards the “Target” which is 90 degrees to the left of the character.

However, when I run the game, when I press “w”, the character will only move for one frame and then stop. I know that this is because the system will process the rotation for one frame. Even after researching for a long time, i can’t find a way to get the character to turn smoothly upon pressing the key.

How is it done? Any help is appreciated.

Tysm! :smiley:

SLERP - we love it!

The third parameter in SLERP is the fraction of the amount to change, in this case your rotation, from 0 to 1. At 0 your rotation is at its staring position, at 1 the ending position. At 0.5, it is halfway through.

In order to use SLERP properly, you need to know the total amount of time you want the transformation to occur in. you can get that by: total time = total rotation amount / speed in degrees per second - if that is your units

Then every frame (your rotate() loop):

slerp fraction += Time.deltaTime / total time

// it’s important to accumulate so += !!!

Then use slerp fraction for your third parameter.