Skip to content

Instantly share code, notes, and snippets.

@SuddenDevelopment
Created March 9, 2023 18:26
Show Gist options
  • Save SuddenDevelopment/16ee11a672421c2fbd69ab4f0ae78773 to your computer and use it in GitHub Desktop.
Save SuddenDevelopment/16ee11a672421c2fbd69ab4f0ae78773 to your computer and use it in GitHub Desktop.
blender python function to orient an object based on a face normal
def faceTheWorld(obj, strMode="EDIT"):
# Thanks to JohnKaz and Kritskiy on BPY Discord for this function, looks simple, but not easy to figure out!
mw = obj.matrix_world.copy()
bm = bmesh.new()
if strMode == 'OBJECT':
bm.from_mesh(obj.data)
else:
bm = bmesh.from_edit_mesh(obj.data)
face = next(iter(face for face in bm.faces if face.select), None)
if not face:
bm.faces.ensure_lookup_table()
face = bm.faces[0]
n = face.normal
t = face.calc_tangent_edge_pair().normalized()
c = face.calc_center_median()
obj.matrix_world = mathutils.Matrix(
(t.cross(n).normalized(), t, n)).to_4x4() @ mathutils.Matrix.Translation(-c)
#use this to return it back to original location with
# obj.matrix_world = the value returned from below
return mw
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment