# Python: Calculate angle between vertices

What should I do to determine the angle on XYZ between two vertices? I then have to rotate a mesh accordingly, but I guess that's a basic task to achieve.

I'm new to bpy and I should have payed more attention during my maths classes, i suppose.

Here's a graphical representation

I need to know the angle of that orange segment

• The angle in relation to what? Aug 1, 2015 at 17:12
• Global x, y and z. Sorry for the omission Aug 1, 2015 at 18:20
• You describe an edge by declaring two vertices. You now need to declare another edge - the x, y, or z unit vectors (only one) - or a plane - the xy, yz, or zx (only one) plane. Aug 1, 2015 at 22:30
• why should I do this? How could it help me with the script? Aug 2, 2015 at 6:51
• Because you can only calculate an angle between two vectors / edges. You might wanna take a vector math course. Aug 2, 2015 at 8:39

You can get two selected vertices via bm.select_history and calculate a direction vector, then measure the angle between this angle and the up vector (0, 0, 1) in radians and convert it to degrees (below script prints the smaller angle):

import bpy
import bmesh
from math import degrees, pi
from mathutils import Vector

ob = bpy.context.object
assert ob.type == 'MESH'
me = ob.data

bm = bmesh.from_edit_mesh(me)
verts_sel = [el for el in bm.select_history if isinstance(el, bmesh.types.BMVert)]
assert len(verts_sel) == 2

v1 = verts_sel[1].co - verts_sel[0].co
v2 = Vector((0, 0, 1))

a1 = v1.angle(v2)
if a1 > pi * 0.5:
a1 = pi - a1
print("{:.2f} degrees".format(degrees(a1)))