- Home /
Quaternion Slerp always rotates to 180
When I press W, A, S or D, it always rotates to 180. Please help me.
public Transform tf;
void FixedUpdate()
{
if (Input.GetKey(KeyCode.W))
{
tf.position += new Vector3(0f , 2f * Time.deltaTime, 0f);
tf.rotation = Quaternion.Slerp(tf.rotation, new Quaternion(0f, 0f, 0f, 0f), 0.2f * Time.deltaTime);
}
if (Input.GetKey(KeyCode.S))
{
tf.position -= new Vector3(0f , 2f * Time.deltaTime, 0f);
tf.rotation = Quaternion.Slerp(tf.rotation, new Quaternion(0f, 0f, 90f, 0f), 0.2f * Time.deltaTime);
}
if (Input.GetKey(KeyCode.D))
{
tf.position += new Vector3(2f * Time.deltaTime, 0f, 0f);
tf.rotation = Quaternion.Slerp(tf.rotation, new Quaternion(0f, 0f, 180f, 0f), 0.2f * Time.deltaTime);
}
if (Input.GetKey(KeyCode.A))
{
tf.position -= new Vector3(2f * Time.deltaTime, 0f, 0f);
tf.rotation = Quaternion.Slerp(tf.rotation, new Quaternion(0f, 0f, -90f, 0f), 0.2f * Time.deltaTime);
}
}
Answer by Pangamini · Aug 24, 2021 at 10:55 PM
First of all, your quaternions don't represent rotations at all. Quaternion representing a rotation is a point on a 4D unit sphere surface. Therefore a valid Quaternion must have a length of 1. Your code new Quaternion(0f, 0f, 90f, 0f)
doesn't do what you think it does. What you are looking for are euler angles. You can create a quaternion from euler angles by using Quaternion.Euler
Slerp doesn't do what you think either. Your code will give you FPS-dependent rotation speeds. That means that your game will behave differently in different situations (and on different PCs). Quaternion.Slerp calculates an interpolated rotation between two input rotations. Whoever came with the original idea that the ratio should include a deltaTime, and put that code online, should be slapped. This is the same with any Lerp function. To rotate from current to target rotation over time, you can use Quaternion.RotateTowards Another option (depends on what behaviour you want) is to store euler angles in a vector, interpolate this vector over time towards the destination euler angles, and calculate a new quaternion from it every Update.
that was a very neat explanation, ive been having troubles with quaternions but this explains it a lot better to me
Your answer
Follow this Question
Related Questions
Quaternion Slerp 180 Away from target 1 Answer
few question about quaternion slerp 3 Answers
How do you check if Quaternion.Slerp has finished 5 Answers
How do I make an object face forward while it is orbiting another object? 1 Answer
By-pass the 'shortest route' aspect of Quaternion.Slerp 1 Answer