The rotation matrix from one vector to another in 2D space

We may need to get the rotation matrix from one vector to another in 2D space, for example, when working with UV maps. This is often necessary to adjust one UV island to another.

To calculate the rotation matrix between two available vectors, first get the angle between these vectors.:

The angle is calculated in radians.

Then we need to understand in which direction we need to rotate. In 2D space, there can be two variants – the original vector is located “above” the second, so we need to rotate counterclockwise, or, if it is “below” – we need to rotate clockwise.

We can get the direction of rotation by the sign of the vector cross product of the two original vectors.

The cross product of two vectors in 2D space is a number whose sign indicates the rotation direction, which is exactly what we need.

If this number is less than zero, the rotation is clockwise. If the number is greater than zero, the rotation is counterclockwise.

As a result, we can regulate the rotation direction by setting the sign to the rotation angle.

Now, using the “Rotation()” method of the “Matrix” object from the “mathutils” module, we can get the rotation matrix.

In the first parameter, we passed the rotation angle. In the second, the size of the matrix – 2×2, which is exactly the matrix we need for rotation in 2D space. In the third parameter, we pass the rotation axis “Z”, which will always be directed perpendicular to the screen.

Let’s put everything together in one function.

Let’s check how our function works for rotating a UV island.

For example, let’s assume that the island is rotated vertically, and we need to rotate it parallel to another island, which is rotated at an angle of 45 degrees.

Then the initial and final vectors for rotation will be as follows:

Based on these vectors, we will get the rotation matrix by calling our function.

Create the bmesh object and get a pointer to the currently active UV-map layer.

Loop through all the selected polygons (for simplicity, let our UV island be selected) and multiply the coordinates of all UV points by the resulting matrix.

And return the updated data from bmesh object back to the common scene mesh.

As we can see, the entire selected island of the UV-Map has rotated exactly as we need – parallel to the other island.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments