- Home /
Vector3.Slerp leads to wrong axis rotation
I need some help with my character movement function. I need my character (for a 3D platformer) to smooth its turns, preferably to the point that the character runs in a perfect circle where a character would normally walk in a square. After scanning the Answers and Forums, I discovered how to use the Slerp() method to smooth rotations, but my result is always different from the results given by other users.
Whenever I start my test, my character is face-down (rotated on the X axis by 90 degrees). Also, when I press a key and release it, the character keeps moving in that same direction (probably caused by the apparent misuse of the Slerp() method).
Here's my function. I can't find anything here that would cause that, so an extra set of eyes would be very helpful. Why won't my solution work?
// This handles movement and rotation.
void BasicMovement()
{
CharacterController controller = GetComponent<CharacterController>();
Vector3 targetDirection;
// If the player is touching the ground, move normally
if (controller.isGrounded)
{
// Take input from the keyboard.
targetDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
// Attempt to smooth from original direction to new direction
moveDirection = Vector3.Slerp(moveDirection, targetDirection, 1.0f * Time.deltaTime);
// Multiply by the move speed and add vertical velocity
moveDirection = (moveDirection.normalized + new Vector3(0, verticalSpeed, 0)) * moveSpeed;
// If the player is moving then handle rotation
if (moveDirection != Vector3.zero)
{
// use SetLookRotation to make characters face where they're going.
Quaternion rotation = transform.rotation;
rotation.SetLookRotation(moveDirection);
transform.rotation = rotation;
}
}
// Only activate gravity if the character is in the air.
if (!controller.isGrounded)
moveDirection.y -= gravity * Time.deltaTime;
// Finally, move the character, according to its frame rate
controller.Move(moveDirection * Time.deltaTime);
}
Answer by whydoidoit · Aug 01, 2012 at 12:37 PM
I think it's probably your two updates to moveDirection - you are both Slerping it then normalizing it. It would be preferable to have another variable in there so the Slerp can operate over multiple frames:
// Take input from the keyboard.
targetDirection = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
// Attempt to smooth from original direction to new direction
currentDirection = Vector3.Slerp(currentDirection, targetDirection, 1.0f * Time.deltaTime);
// Multiply by the move speed and add vertical velocity
moveDirection = (currentDirection.normalized + new Vector3(0, verticalSpeed, 0)) * moveSpeed;
Your answer
Follow this Question
Related Questions
Transforming slowly 1 Answer
move object and slow down near end 1 Answer
Slerp to make the right/left side face another object 2 Answers
Interpolating along an arc. 1 Answer
Having a issue with Vector3.Slerp 1 Answer