Blender modal operator cannot insert keyframe and move object

Viewed 498

In Blender I am using the modal operator template to move an object and record its position as a keyframe.

I am doing something like this:

import bpy
from bpy.props import IntProperty, FloatProperty

class ModalOperator(bpy.types.Operator):
    """Move an object with the mouse, example"""
    bl_idname = "object.modal_operator"
    bl_label = "Simple Modal Operator"

    first_mouse_x = IntProperty()
    first_value = FloatProperty()
    current_frame = 1
    endframe = bpy.data.scenes["Scene"].frame_end

    def modal(self, context, event):
        if event.type == 'MOUSEMOVE':
            if self.current_frame < self.endframe:
                delta = self.first_mouse_x - event.mouse_x
                context.object.location.x = self.first_value + delta * 0.01
                context.scene.frame_set(self.current_frame)
                bpy.ops.anim.keyframe_insert_menu(type="Rotation")
                bpy.ops.anim.keyframe_insert_menu(type="Location")
                self.current_frame+=1

        elif event.type == 'LEFTMOUSE':
            return {'FINISHED'}

        elif event.type in {'RIGHTMOUSE', 'ESC'}:
            context.object.location.x = self.first_value
            return {'CANCELLED'}

        return {'RUNNING_MODAL'}

Happens that before it inserts all keyframes and only after you can move the cube with the mouse, for instance. I would like to move the cube and "record" its movement at the same time. Is there a solution for that?

2 Answers

The easy solution would be to enable blenders Auto Keyframing.

If you still want to get your operator working, I expect you will need to not call other operators and work with the data directly, particularly within a modal operator.

context.object.keyframe_insert('location')
context.object.keyframe_insert('rotation_euler')

Ok I solved this one.

I was calling the keyframe_insert for the wrong object (anim, instead of the cube itself)

This is the proper way to insert it, for example when the object is a camera:

camera = bpy.context.scene.camera
camera.keyframe_insert(data_path='location', index=0)
camera.keyframe_insert(data_path='location', index=1)
camera.keyframe_insert(data_path='location', index=2)
camera.keyframe_insert('rotation_quaternion')

in this way the keyframes are inserted on play.

Related