1
$\begingroup$

I am writing an importer in Blender that appends a object and then moves and rotates that object by some stored values I have created in Unity and saved to a Json file.

I found that in order to achieve the desired rotation I must first set my object to rotation_mode='YXZ' then I can create a new Vector with the order (X,Z,-Y) and my object will be rotated correctly:

degToRad = math.pi / 180

myobj.rotation_mode = 'YXZ'
jRot = json['rotation']
myobj.rotation_euler = Vector((jRot['x']*degToRad, jRot['z']*degToRad, -jRot['y']*degToRad ))

#Do something here to convert rotation back to XYZ...

myobj.rotation_mode = 'XYZ' #this causes the object to rotate unexpectedly 

But when I attempt to revert the rotation_mode back to XYZ the object then rotates to some other orientation and I don't know how to prevent.

I am not sure if I am correctly changing handedness and up/forward with my above example but it seems to work ok.

I am curious if it is possible to change the rotation_mode from YXZ to XYZ without the orientation of my object changing?

Or is it possible to somehow apply a "converted" rotation so I can just keep the rotation_mode as XYZ?

Thanks for help!

$\endgroup$
0
2
$\begingroup$

You can use matrices, or quaternions. Unlike euler rotations, matrices or quaternions are comprised values which are order-independent.

There is no need to apply the "wrong" YXZ rotation to the object. You can store it in an mathutils.Euler object, the convert it to a mathutils.Matrix object and finally convert it back using a different rotation order.

import bpy
import mathutils

ob = bpy.context.active_object

x, y, z = 1, 2, 3

rot_YXZ = mathutils.Euler((x, y, z), 'YXZ')
rot_mat = rot_YXZ.to_matrix()
rot_XYZ = rot_mat.to_euler('XYZ')

ob.rotation_mode = 'XYZ'
ob.rotation_euler = rot_XYZ

The mathutils.Matrix.to_euler method takes the desired rotation order as the first argument.

$\endgroup$
2
  • $\begingroup$ That was a wonderful explanation and a perfect solution. Thank you so much! $\endgroup$ – Logic1 Sep 16 '19 at 13:35
  • 1
    $\begingroup$ Glad it helped, the mathutils module provides many useful conversion methods. For a deeper understanding I recommend this video as an introduction to the math of quaternion rotations, if you are interested in the logic behind these functions. $\endgroup$ – Leander Sep 16 '19 at 14:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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