1
$\begingroup$

I have a rotated and scaled cube (on all axis) with the rotation and scale applied. For example:

enter image description here

As I don't know the original rotation and scale, using Python I'd like to align the cube along the global x,y & z axis. For example, the desired result would be:

enter image description here

For my test I've created a randomly rotated and scaled cube:

import bpy, random

bpy.ops.mesh.primitive_cube_add(size=1)
cube = bpy.context.active_object

cube.rotation_euler = (
   random.uniform(-100,100),
   random.uniform(-100,100),
   random.uniform(-100,100)
)

cube.scale = (
    random.uniform(.5,1.5),
    random.uniform(.5,1.5),
    random.uniform(.5,1.5)
)

# I won't know the rotation or scale before they were applied
bpy.ops.object.transform_apply(location=False, rotation=True, scale=True)

To align the cube, I've managed to get almost there using the following technique:

mesh_data = cube.data

for edge in mesh_data.edges:
    
    #Get the vertex indices from the edge
    vertex_index_1, vertex_index_2 = edge.vertices

    #Actual edge vetrices
    vertex_co_1 = mesh_data.vertices[vertex_index_1].co
    vertex_co_2 = mesh_data.vertices[vertex_index_2].co
    
    #Calculate a direction from the vertices
    edge_direction = (vertex_co_2 - vertex_co_1)
    edge_direction.normalize()
    
    #Get a rotation from the direction
    rotation_matrix = edge_direction.to_track_quat('Z', 'Y').to_matrix().to_4x4()
    
    #Transpose
    rotation_matrix_transposed = rotation_matrix.transposed()
    
    #Apply
    cube.matrix_world = rotation_matrix_transposed
        
    bpy.context.view_layer.update()
    
    break

However, this only aligns one of the faces along one of the axis. Hoping someone can spot the problem!

$\endgroup$
3
  • 1
    $\begingroup$ Loot at my answer here: Aligning objects $\endgroup$ Commented Dec 14, 2023 at 21:07
  • $\begingroup$ Thanks Markus, that's helpful. The use-case is for export to game engine box colliders. $\endgroup$
    – FredL
    Commented Dec 15, 2023 at 11:07
  • $\begingroup$ Here is a more general solution: blender.stackexchange.com/a/290025/76897 for optimizing game engines box collisions. $\endgroup$
    – unwave
    Commented Dec 15, 2023 at 16:28

0

You must log in to answer this question.

Browse other questions tagged .