Created
June 9, 2023 08:25
-
-
Save Cosmo/a95fa45bace96a39e97b68747016807c to your computer and use it in GitHub Desktop.
Blender: Move Object to the floor's center (0,0,0)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import bpy | |
# Get the current context | |
current_context = bpy.context | |
# Iterate through all selected objects | |
for obj in current_context.selected_objects: | |
# Get the object's world matrix | |
world_matrix = obj.matrix_world | |
# Calculate the minimum Z coordinate (lowest point) of the object | |
min_z = min((world_matrix @ vertex.co)[2] for vertex in obj.data.vertices) | |
world_matrix.translation.z -= min_z | |
# Calculate the average X and Y coordinates (center) of the object | |
avg_x = sum((world_matrix @ vertex.co)[0] for vertex in obj.data.vertices) / len(obj.data.vertices) | |
avg_y = sum((world_matrix @ vertex.co)[1] for vertex in obj.data.vertices) / len(obj.data.vertices) | |
# Move the object to the center in X and Y coordinates | |
world_matrix.translation.x -= avg_x | |
world_matrix.translation.y -= avg_y | |
# Set the 3D cursor to the floor at (0, 0, 0) | |
bpy.context.scene.cursor.location = (0, 0, 0) | |
# Save the previous pivot point setting | |
previous_pivot_point = bpy.context.scene.tool_settings.transform_pivot_point | |
# Set the pivot point to the 3D cursor | |
bpy.context.scene.tool_settings.transform_pivot_point = 'CURSOR' | |
# Iterate through all selected objects again | |
for obj in current_context.selected_objects: | |
# Set the object's origin to the 3D cursor without moving the object | |
bpy.ops.object.select_all(action='DESELECT') | |
obj.select_set(True) | |
bpy.context.view_layer.objects.active = obj | |
bpy.ops.object.mode_set(mode='EDIT') | |
bpy.ops.mesh.select_all(action='SELECT') | |
bpy.ops.object.mode_set(mode='OBJECT') | |
bpy.ops.object.origin_set(type='ORIGIN_CURSOR', center='BOUNDS') | |
# Restore the previous pivot point setting | |
bpy.context.scene.tool_settings.transform_pivot_point = previous_pivot_point |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment