actually I making some extraobjects, and I want to add the feature "align object to view" but I don't know how..

I check the Align object to view with Python but I don't understand how apply in my task

here the addon working: http://pastebin.com/eW0Vu2EQ

thanks for any help


You can retrieve the required matrix from the view_matrix attribute of the 3D View space. It needs to be transposed and values in the 4th row and column be reset. Finally, you may set the translation components to the cursor location to get the behavior in line with the standard mesh add operators:

import bpy
import bmesh

class SimpleOperator(bpy.types.Operator):
    bl_idname = "object.simple_operator"
    bl_label = "Simple Object Operator"

    def poll(cls, context):
        return context.mode == 'OBJECT' and context.area.type == 'VIEW_3D'

    def execute(self, context):

        scene = context.scene

        bm = bmesh.new()

        me = bpy.data.meshes.new("Cube")

        ob = bpy.data.objects.new("Cube", me)
        mat = context.space_data.region_3d.view_matrix.transposed().to_3x3().to_4x4()
        mat.translation = scene.cursor_location
        ob.matrix_world = mat


        return {'FINISHED'}

def register():

def unregister():

if __name__ == "__main__":

    for area in bpy.context.screen.areas:
        if area.type == 'VIEW_3D':
            ctx = bpy.context.copy()
            ctx["area"] = area
            ctx["region"] = area.regions[-1]
            ctx["space_data"] = area.spaces.active

While you can use the view_matrix to alter the orientation of your model, I would say don't.

Blender has a user preference for aligning new objects to view or global orientation. You should honour the users choice and not make your addon act 'weird' to the user.

After mesh.from_pydata() make a call to object_data_add() which will

Add an object using the view context and preference to to initialize the location, rotation and layer.

  • $\begingroup$ Look at the very bottom of your Tool Shelf (T) after adding a new object from your preferred viewing angle. Check the box "Align to View". Delightful. $\endgroup$ Jun 9 '18 at 5:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.