How to use rotations in 2D?

When using quaternions in 2D, only one of the axis are used. How do I translate the normal one axis rotations used in 2D games to the quaternion used by the Sprite.transform.rotation? I’m specifically thinking of instantiating a missile in a direction, but I don’t know what rotation to use.

Quaternion.AngleAxis() works. Use Vector3.forward as the axis. Given a vector from your origin, Mathf.Atan2 will calculate an angle. Vector3.right is the 0.0 degree reference for that rotation. Atan2() returns radians, so be sure to use Mathf.Rad2Deg with the result.

If you are using 3D objects in a 2D setup where the ‘forward’ of those objects aim a positive ‘z’ when the roation is (0,0,0), then Transform.LookAt() and Quaternion.LookRotation() will work. Both functions have an optional second parameter that defines ‘up’. For 2D on the XY plane, you need this optional second parameter, and it should be set to Vector3.forward.

So if you have a direction for your missle, the code might look like:

var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vectore3.forward);

This assumes that the head of the missile points towards Vector3.right when the rotation is (0,0,0).

If you are using a 3D missile of the correct rotation, then the code might be:

transform.rotation = Quaternion.LookRotation(dir, Vector3.forward);