I want to animate a body using an external file with x, y, z coordinates and quaternion data.

In the file every entry [x,y,x,q0,q1,q2,q3] represents a frame to be rendered.

I heard about Blender and its compatibility with python and, since I am a python user, I would like to know if it is possible to do what I mentioned above and how to do it.

Thanks in advance.


1 Answer 1


It's very possible, and doesn't even sound difficult to do.

Make sure Object.rotation_mode is 'QUATERNION' (once for the object):

ob = bpy.context.object # active object, assuming there is one
ob.rotation_mode = 'QUATERNION'

Reading the file:

import bpy
from mathutils import Vector, Quaternion

file = open("input.txt", "r")
for line in file:
    x, y, z, q0, q1, q2, q3 = line.strip(" \t\r\n[]").split(",")
    loc = float(x), float(y), float(z)
    quat = float(q0), float(q1), float(q2), float(q3)

    # Or cast to Vector / Quaternion type if you need any methods of them later
    #loc = Vector(loc)
    #quat = Quaternion(quat)

I assume line 1 in the file is meant to be the first frame in Blender and so on. Let's keep track of the line number:

for i, line in enumerate(file, 1):

Assign the location and the rotation in our for-loop:

    ob.location = loc
    ob.rotation_quaternion = quat

and insert keyframes for frame i:

    ob.keyframe_insert('location', frame=i)
    ob.keyframe_insert('rotation_quaternion', frame=i)

Finally, we close the file:


For a better performaning way to animate with python, see:


  • $\begingroup$ Thank you so much for your help. It works! I just want to add something: loc and quat can't have string entries so they must be transform to float. $\endgroup$
    – Tharek M
    Feb 12, 2014 at 0:33
  • $\begingroup$ Geez! Totally forgot to cast to numbers, edited my post. float() accepts any kind of floating point notation: 0.1, .1, 1., 1e-3. For integer values, you would use int() (no rounding if used on floats, use math.round() instead if needed). Properties like Object.location accept several types without explicit casting, Vector, int, float... $\endgroup$
    – CodeManX
    Feb 12, 2014 at 0:41

You must log in to answer this question.

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