You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Godot:如何通过代码修改动画关键帧中的节点位置

Hey there! Let's fix that code so you can dynamically update the target position of your move animation.

Your initial approach is on the right track, but the issue is that directly modifying the Keyframe object from get_keyframe() won't work as expected—Godot's Animation system organizes keyframes by tracks (each track controls a specific property like position), so we need to target the correct track first.

Here's the corrected code that will properly update the position of your second keyframe:

func moveTo(pos: Vector2):
    # Get references to your AnimationPlayer and the "move" animation
    var anim_player = get_node("animation")
    var move_anim = anim_player.get_animation("move")
    
    # Find the track index for the position property (adjust the path if needed)
    # If your animation targets the current node's position, the path is "."
    var position_track = move_anim.find_track("position")
    
    if position_track != -1:
        # Update the value of the 1st index keyframe (since your animation has two keyframes: 0 = start, 1 = end)
        move_anim.set_keyframe_value(position_track, 1, pos)
    
    # Play the updated animation
    anim_player.play("move")

A quick breakdown of why this works:

  • find_track("position") locates the track that controls the node's position property. If your animation uses a different property (like global_position), just replace "position" with that.
  • set_keyframe_value() is the proper method to modify a keyframe's value—this ensures the animation resource actually updates, unlike trying to modify the Keyframe object directly.
  • We check if position_track != -1 to avoid errors in case the track doesn't exist (good practice!).

If you set up your animation with only the position track, you could also skip find_track() and just use 0 as the track index, but using find_track() makes the code more robust if you ever add other tracks later.

内容的提问来源于stack exchange,提问作者JCAguilera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:37:56