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.

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?

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);