Smooth rotation of characters

Here is my code for moving in four main directions:

if (Input.GetKeyDown(KeyCode.RightArrow)){ transform.forward = new Vector3(0f, 0f, 1f); } else if (Input.GetKeyDown(KeyCode.LeftArrow)){ transform.forward = new Vector3(0f, 0f, -1f); } else if (Input.GetKeyDown(KeyCode.DownArrow)){ transform.forward = new Vector3(1f, 0f, 0f); } else if (Input.GetKeyDown(KeyCode.UpArrow)){ transform.forward = new Vector3(-1f, 0f, 0f); } 

My character instantly rotates in four directions of travel. The problem I am facing is figuring out how I can smooth out intermediate directions. I'm trying to say if the character points to the north, and you press the button to go west, and not immediately turn to the west, I would like the character to smoothly rotate in degrees towards the west.

I searched and tried textbooks, but none of them worked. Any solution?

+4
source share
1 answer

Take a look at the Slerp function. This will probably do what you want.

http://unity3d.com/support/documentation/ScriptReference/Quaternion.Slerp.html

A simple example:

  newdir.y=-135; // depends on which axis you want to turn... transform.rotation = Quaternion.Lerp(transform.rotation, newdir, Time.deltaTime * smoothSpeed); 

So, you basically get the Quaternion of your current rotation. Copy this into the new quaternion and increase or decrease the rotation on one or more axes.

+4
source

Source: https://habr.com/ru/post/1379855/


All Articles