# How to keyframe_insert without moving the object

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 want to insert keyframe and not move the object on the screen.

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

• at the beginning of your code, you can "current_frame = bpy.context.scene.frame_current" and at the end "s.frame_set(current_frame)" – lemon Oct 20 at 12:25
• @lemon I think you should post that as an answer. – Robert Gützkow Oct 20 at 13:18

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.

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