0
$\begingroup$

I am stuck on a problem in Blender. I am trying to create a function that automatically aligns an object based on its dimensions to the world axis. This mean for example the largest axis will be aligned with the X axis and so on....

The function should get an order of the axis as input which should than align the dimensions accordingly.

My current logic is the following:

def align_object(obj, axis_order):
    # Ensure obj is the active object
    bpy.context.view_layer.objects.active = obj
    bpy.ops.object.mode_set(mode='OBJECT')

    # Get the dimensions
    dimensions = obj.dimensions

    # Create a mapping from dimensions to axis
    dim_to_axis = {'X': dimensions[0], 'Y': dimensions[1], 'Z': dimensions[2]}
    sorted_dims = sorted(dim_to_axis.items(), key=lambda x: x[1], reverse=True)

    # Match the sorted dimensions to the input axis order
    target_axes = {axis_order[i]: sorted_dims[i][0] for i in range(3)}

    # Calculate the necessary rotations
    # This is a simplified example; actual implementation may need more complex math
    rotations = mathutils.Euler((0, 0, 0), 'XYZ')
    for target_axis, current_axis in target_axes.items():
        if current_axis != target_axis:
            if (current_axis, target_axis) in [('X', 'Y'), ('Y', 'Z'), ('Z', 'X')]:
                rotations.rotate_axis(target_axis, math.pi / 2)
            else:
                rotations.rotate_axis(target_axis, -math.pi / 2)

    # Apply the rotation
    obj.rotation_euler = rotations

Example usage

obj = bpy.context.active_object
align_object(obj, ['X', 'Y', 'Z'])

But here are always problems with rotations are applied multiple times or it just does not go to the write alignment.

In case someone can have a look at it, I would really appreciate it.

Cheers

$\endgroup$
1

0

You must log in to answer this question.

Browse other questions tagged .