# How to automatically rotate an object on its local z axis to make one of its edges parallel to that of another object

I made a video to better explain what I ask in the title. When I say "parallel to this edge" perhaps it would be more correct to say "parallel to the projection of this edge to the floor"I hope someone can help me

• Have you considered a driver? Commented Mar 19, 2021 at 2:07

Via a script.

Getting the angle is relatively simple here. The 3d vector v projected onto Z = 0 plane is simply v.xy ie its x and y coordinates. The signed angle between two 2d vectors is

v1.angle_signed(v2)


Related Face edges angle - python re projecting into any plane, eg the face normal of target plane.

Once we have this angle can rotate the target mesh by it about its Z axis.

Example script.

Here is an example script with both objects in edit mode. The last selected edge also makes the object the target object to be rotated. Note, this relies on the two objects NOT sharing a mesh. (If they did there would be no way to select a different edge in each while both in edit mode)

import bpy
import bmesh
from mathutils import Matrix
from itertools import product
context = bpy.context

ob = context.object
bm = bmesh.from_edit_mesh(ob.data).copy()
bm.transform(ob.matrix_world)
e0 = bm.select_history.active
mw0 = ob.matrix_world
# find closest verts
for o  in context.selected_objects:
if o is ob or o.type != 'MESH':
continue
bm1 = bmesh.from_edit_mesh(o.data).copy()
bm1.transform(o.matrix_world)
e1 = bm1.select_history.active
# find the two closest verts
v0, v1 = sorted(
product(e0.verts, e1.verts),
key= lambda e: (e[1].co - e[0].co).length
).pop()
angle = (e0.other_vert(v0).co - v0.co).xy.angle_signed((v1.co - e1.other_vert(v1).co).xy)
print(angle)
# rotate angle about ob origin
R = (
Matrix.Translation(mw0.translation) @
Matrix.Rotation(-angle, 4, 'Z') @
Matrix.Translation(-mw0.translation)
)
ob.matrix_world = R @ mw0

• First of all thanks for the help. Unfortunately, however, I was unable to understand much. Both because I'm not very good with English and because I've never used scripts. Basically I did not understand what are the steps to do and under what conditions to do them. Should I first select the two edges in edit mode and then paste your script in the script workspace? Do I need to do something with "v1.angle_signed (v2)" first? Where should I write this? In what condition? Edit mode? Do I have to select the edges? Sorry... Commented Mar 19, 2021 at 14:34
• I'm still blundering around in the dark....... Commented Mar 27, 2021 at 23:29