1
$\begingroup$

I’m trying to import a model, set its location it and rotate the whole model using the quaternion mode.

Here’ s my code:

bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete() 
bpy.ops.import_scene.obj(filepath='Bench_1.obj', axis_forward='-Z', axis_up='Y')
object = bpy.context.selected_objects
for obj in bpy.context.selected_objects:
    if obj.type == 'MESH':
        obj.location.x = 5
        obj.location.z = 5
        obj.location.y = 5
        obj.rotation_mode = "QUATERNION"
        obj.rotation_quaternion.x = 1 
        obj.rotation_quaternion.y = 1
        obj.rotation_quaternion.z = 0
        obj.rotation_quaternion.w = 1
        bpy.context.scene.update() 

It works fine, but in this case model’s pivot point is right in the center. enter image description here

Some other models may have pivot point far away from geometry, so I can’t neither locate, nor rotate them properly. I decided to put an extra line in my code that will always set pivot point in the center of any imported model:

bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete() 
bpy.ops.import_scene.obj(filepath='Bench_1.obj', axis_forward='-Z', axis_up='Y')
object = bpy.context.selected_objects
bpy.ops.object.origin_set(type='ORIGIN_CENTER_OF_MASS') # EXTRA LINE HERE!
for obj in bpy.context.selected_objects:
    if obj.type == 'MESH':
        obj.location.x = 5
        obj.location.z = 5
        obj.location.y = 5
        obj.rotation_mode = "QUATERNION"
        obj.rotation_quaternion.x = 1 
        obj.rotation_quaternion.y = 1
        obj.rotation_quaternion.z = 0
        obj.rotation_quaternion.w = 1
        bpy.context.scene.update() 

After this update my ‘normal’ models become fractured:

enter image description here

What am I doing wrong?

$\endgroup$

1 Answer 1

1
$\begingroup$

I suspect that all of the points in the geometry are relative to the origin, but that likely does not explain the problem you are experiencing. I found this function in a previous answer, it seems to move the pivot point without the problems you are experiencing.

import bpy
from mathutils import Vector, Matrix

def set_origin(ob, global_origin=Vector()):
    mw = ob.matrix_world
    o = mw.inverted() @ Vector(global_origin)
    ob.data.transform(Matrix.Translation(-o))
    mw.translation = global_origin
    
# call the function:
set_origin(bpy.context.object)
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .