1
$\begingroup$

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?

enter image description here

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

2 Answers 2

3
$\begingroup$

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)

bpy.context.scene.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.

$\endgroup$
2
  • $\begingroup$ what is s in this example ? $\endgroup$ Aug 28, 2023 at 22:58
  • $\begingroup$ @VictorPowell, this is the scene (corrected). $\endgroup$
    – lemon
    Aug 30, 2023 at 12:25
2
$\begingroup$

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
$\endgroup$

You must log in to answer this question.

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