How to insert keyframe_insert without moving the object

by taichi   Last Updated October 20, 2019 05:15 AM - source

I tried the following code:

import bpy

obj = bpy.data.objects['Cube']
obj.keyframe_insert(data_path='location', frame=0)
obj.location.z += 5
obj.keyframe_insert(data_path='location', frame=100)

Then, after executing the code, the Cube position moves in the Z direction.

But, I just want to insert keyframe and not move the object on the screen.

How can I insert keyframes without moving objects on the screen?

enter image description here

Tags : python scripting


Answers 2


You can surround your code with something like:

current_frame = bpy.context.scene.frame_current

obj = bpy.data.objects['Cube']
obj.keyframe_insert(data_path='location', frame=0)
obj.location.z += 5
obj.keyframe_insert(data_path='location', frame=100)

s.frame_set(current_frame)

So that the current (or the frame you want) is restored once the key frames are inserted.

Though, that does not guaranty that the object will not move, as its movement is dependent on the key frames you have set.

lemon
lemon
October 20, 2019 14:15 PM

To keyframe an object without moving the object or changing the current frame, you can create a keyframe with the current location and then get the keyframe data and change it to the desired position.

import bpy

def key_z_at_frame(o, at_frame, loc):
    o.keyframe_insert(data_path='location', frame=at_frame)
    act = o.animation_data.action
    fc = act.fcurves.find('location', index=2)
    for kp in fc.keyframe_points:
        if kp.co[0] == at_frame:
            kp.co[1] = loc

obj = bpy.context.object
cur_frame = bpy.context.scene.frame_current
key_z_at_frame(obj, cur_frame, obj.location.z)
key_z_at_frame(obj, 100, 5)

If the frame you want to add is always going to be at the highest frame number, you could replace the loop with

fc.keyframe_points[-1].co[1] = loc
sambler
sambler
October 27, 2019 09:21 AM

Related Questions



How to create a Folder Dialog?

Updated April 04, 2015 21:06 PM

Mesh's material_index is an index into what?

Updated April 17, 2015 20:06 PM


OS cursor location in Blender Windows

Updated March 29, 2015 06:05 AM