- Home /
How to use Quaternion to rotate an object in only one axis?
Hi, I'm trying to use Quaternion to rotate my 2d object to face the direction of movement. Code:
Vector3 dir = (transform.position - lastPosition).normalized;
Quaternion rot = Quaternion.FromToRotation(forward, dir);
transform.rotation = Quaternion.Lerp(transform.rotation, rot, Time.deltaTime * 20);
dir is the direction of movement. forward is a local variable initialized to (1,0,0).
For the most part it works. However, in rare occasions, the Quaternion chooses to rotate around the y-axis instead of the z-axis (up), causing the 2d sprite to into the background.
Is there a way to force it to use the z-axis every time?
What is 'forward' here? Is it 'transform.forward' or does it refer to some other direction?
Hi, just updated the description. "forward" is a local variable initialized to (1,0,0).
Answer by robertbu · Jan 21, 2014 at 11:41 PM
Since you are using the 'right' side of your 2D object as forward, try this:
Vector3 dir = transform.position - lastPosition;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
Quaternion rot = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, rot, Time.deltaTime * 20);
Your answer
Follow this Question
Related Questions
Rotate towards target position (mouse) at a limited speed 1 Answer
Problem with normal snapping and rotations. 1 Answer
Rotate floor plane in-game via C# script 1 Answer
How do you rotate an object with Vector that has another vector defining its angle 0 Answers
Quaternion.LookRotation and Vector3.SmoothDamp Problems 1 Answer