0
$\begingroup$

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

$\endgroup$
4
$\begingroup$

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):
    """Tooltip"""
    bl_idname = "object.simple_operator"
    bl_label = "Simple Object Operator"

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

    def execute(self, context):

        scene = context.scene

        bm = bmesh.new()
        bmesh.ops.create_cube(bm)

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

        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

        scene.objects.link(ob)
        scene.update()

        return {'FINISHED'}


def register():
    bpy.utils.register_class(SimpleOperator)


def unregister():
    bpy.utils.unregister_class(SimpleOperator)


if __name__ == "__main__":
    register()

    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
            bpy.ops.object.simple_operator(ctx)
            break
| improve this answer | |
$\endgroup$
2
$\begingroup$

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.

| improve this answer | |
$\endgroup$
  • $\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$ – Coby Randal Jun 9 '18 at 5:38

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