Smooth Rotation on WASD keys pressed?

Hello there,

I have been searching for the longest time for a way for my player to rotate smoothly on each key pressed.
I’ve tried everything available to attempt to get it to work, so, here I am.

I am 80% sure that I haven’t got the most efficient movement script, but it works. I’m more than willing to improve it later but for now, I would just like to know how I can get my player to rotate smoothly.

when I press “W” my player moves in the desired direction, the same goes for “A”, “S”, and “D”. I do this using rigidbody.velocity. like this - rb.velocity = new vector3 (0, 0, 4); (rb = Rigidbody). there is definitely a better way of moving probably using time.deltatime or something.

I also have this working at an angle so when “W” and “D” are pressed for example, it moves 45 degrees in the right direction.

My Rotation code is the problem as far as i’m concerned, I’m hoping you can tell me if there is something i can add for smooth rotation from “D” to “W” for example.

My rotation code is this - transform.localRotation = quaternion.Euler(-90, -90, 0); this rotates my player (a rectangular box) to face the key pressed. However, the rotation is snappy. Is there a way using Lerp or Slerp or something else that can rotate my player to face the right direction in a smooooth way.

Sorry about the long winded question, I just want to be extremely thorough for your better understanding.

I haven’t got much experience with code since I’m more about the art stuff so go easy :wink:

(C# code if any please.)

Thanks in advance

Hello!

To make things smoother try to set the variables time based. So given that you want to get something from a to b you can use a variable starting with a and add delta time and clamp it to make it the desired. Also moving a variable from 0 to 1 and using lerp you can make even more things smoother.

float t = 0f;
float animSpeed = 1f;
bool animate = false;
    
void Update()
    {
    if(animate)
    {
    t += animSpeed * Time.deltaTime*speed;
    t = Mathf.Clamp01(t);
    transform.rotation = Quaternion.Slerp(from, to, t);
    }else
    {
    t = 0f;
    }
}

you can set the from to the current rotation you have and set the to to the desired rotation, in your example
from = Quaternion.identity;
to = Quaternion.Euler(-90, -90, 0);

Also this just interpolates between the from and to. When I want to make things even smoother I add a function

float smooth(float t)
{
return 3*t*t-2*t*t*t;
}

And instead Slerp(from, to, t) you can use Slerp(from, to smooth(t));
and it will make animations even smoother.

Hope it helps!