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

Godot C#:从AnimationTree获取BlendSpace2D状态及解决Travel报错

解决Godot C#中AnimationTree的Travel方法调用错误问题

问题原因

你遇到的错误核心是类型不匹配:

  • GDScript中_animationTree.Get("parameters/playback")返回的是AnimationNodeStateMachinePlayback类型对象,它才拥有Travel()方法。
  • 但你在C#代码中将_animationState声明为AnimationTree类型,而AnimationTree本身并没有Travel()方法,因此编译器报错。
  • 另外,获取playback节点的方式错误,不能用GetNode(),必须通过AnimationTree.Get()方法访问其内部参数节点。

修正步骤

  1. 修正_animationState的类型声明为AnimationNodeStateMachinePlayback
  2. 在_Ready()方法中正确获取playback节点并转换类型
  3. 确保Travel()的参数与AnimationTree状态机中的状态名称完全一致(大小写敏感)

修正后的完整代码

using Godot;
using System;

public class Player : KinematicBody2D
{
    // CHARACTER MOVING STUFF
    public const int run_acc = 80;
    public const int max_speed = 100;
    public const int friction = 500;
    
    public Vector2 velocity = new Vector2();
    // ANIMATION RELATED
    private AnimationPlayer _animationPlayer;
    private AnimationTree _animationTree;
    private AnimationNodeStateMachinePlayback _animationState; // 修正类型
    
    public override void _Ready()
    {
        _animationPlayer = GetNode<AnimationPlayer>("AnimationPlayer");
        _animationTree = GetNode<AnimationTree>("AnimationTree");
        // 正确获取playback节点并转换类型
        _animationState = _animationTree.Get("parameters/playback") as AnimationNodeStateMachinePlayback;
    }

    public override void _PhysicsProcess(float delta)
    { 
        var input_vector = Vector2.Zero;
        input_vector.x = Input.GetActionStrength("move_right") - Input.GetActionStrength("move_left");
        input_vector.y = Input.GetActionStrength("move_down") - Input.GetActionStrength("move_up");
        input_vector = input_vector.Normalized();
        
        if (input_vector != Vector2.Zero)
        {
            _animationTree.Set("parameters/idle/blend_position", input_vector);
            _animationTree.Set("parameters/run/blend_position", input_vector);
            _animationState.Travel("Run"); // 现在可以正常调用Travel
            velocity = velocity.MoveToward(input_vector * max_speed, run_acc);
        }
        else
        {
            _animationState.Travel("Idle"); // 正常调用Travel
            velocity = velocity.MoveToward(Vector2.Zero, friction * delta);
        }
        velocity = MoveAndSlide(velocity);
    }
}

额外注意事项

  • 确认AnimationTree状态机中的状态名称(Idle、Run)与代码中的字符串完全一致,Godot对字符串大小写敏感。
  • 检查BlendSpace2D的参数路径(parameters/idle/blend_position、parameters/run/blend_position)是否与你的AnimationTree结构匹配,路径错误会导致动画不切换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 02:35:19