动画播放器树如何使用gdscript (Godot 4.0)

Kay*_*ush 2 gdscript godot

在我的脚本中实现动画时遇到问题

extends CharacterBody2D


const SPEED = 300.0
const JUMP_VELOCITY = -400.0

var gravity = ProjectSettings.get_setting("physics/2d/default_gravity")


func _physics_process(delta):
    # Add the gravity.
    if not is_on_floor():
        velocity.y += gravity * delta

    # Handle Jump.
    if Input.is_action_just_pressed("ui_accept") and is_on_floor():
        velocity.y = JUMP_VELOCITY

    # Get the input direction and handle the movement/deceleration.
    # As good practice, you should replace UI actions with custom gameplay actions.
    var direction = Input.get_axis("left", "right")
    if direction:
        velocity.x = direction * SPEED
    else:
        velocity.x = move_toward(velocity.x, 0, SPEED)
        

    move_and_slide()

#having a hard time adding animation tree 
Run Code Online (Sandbox Code Playgroud)

我尝试将动画播放器添加到脚本中。并将其指向动画树,但我无法让它根据指示播放动画

The*_*aot 7

AnimationTree原则上,您根本不需要与代码的表单进行交互。

您需要的是设置一个AnimationPlayer您想要的动画,然后设置一个AnimationTree,确保:

  • anim_player指向您的AnimationPlayer(默认情况下不指向任何内容)。
  • advance_expression_base_node指出一些有用的东西。我建议将其设置为您的CharacterBody2D(默认情况下它指向自身AnimationTree)。
  • tree_root不为空。我建议设置为新的AnimationNodeStateMachine.
  • active被设定为true

当然,您需要在编辑器底部出现的“AnimationTree”面板中制作实际的动画树。

如果您使用AnimationNodeStateMachineroot,则可以在“动画树”面板中使用动画(或混合速度或其他状态机)设计图形。例如,您可以将一个Idle动画连接到另一个Walking动画并返回。

在动画之间的过渡中,决定是否必须等待动画完成,在这种情况下将它们设置switch_mode为“结束时”,否则将它们设置为“立即”。

您可以编写一个表达式来控制属性中节点之间的转换advance_expression。例如,您可以设置它velocity.is_zero_approx()以过渡到空闲动画。这样戈多就可以切换动画了。

您可能还想设置xfade_time,也许xfade_curve还想设置 ,因为它们控制动画混合。


如果您确实想AnimationTree从 GDScript 中进行操作,请首先在脚本中获取对它的引用。您可以按住 CTRL 键将其拖动到脚本中,让 Godot@onready var为其生成一个脚本。

例如:

@onready var animation_tree:AnimationTree = $AnimationTree
Run Code Online (Sandbox Code Playgroud)

选择后,AnimationTree您可以在检查器中看到它有哪些参数。然后您可以从 GDScript 访问它get(您可以通过在检查器中二次单击属性来从上下文菜单中复制属性路径)。

例如:

var playback:AnimationNodeStateMachinePlayback = animation_tree.get("parameters/playback")
Run Code Online (Sandbox Code Playgroud)

在示例中,我们获得了 的回放AnimationNodeStateMachine,我们可以用它来告诉状态机转到我们想要的节点travel。例如:

playback.travel("some_state")
Run Code Online (Sandbox Code Playgroud)

当然,如果您需要操作图表,您也可以访问tree_root代码AnimationTree