Home > Software engineering >  How to set a Sprite to a specific Frame in Godot
How to set a Sprite to a specific Frame in Godot

Time:01-13

I have the Player move around and when he enters a new Room (via Instancing) his Sprite shows him facing in the Default direction (in my Case down). So If you enter a Room from any other direction then it looks weird, cause for a short Moment you can see the Player facing down even if you came from the right. How can I tell Godot to set the Player Sprite to a specific Frame in Code, so I can set it to the proper Frame for each Direction. I'm new to Godot and I used HeartBeast Action RPG Tutorial for my Movement. So it's using an AnimationTree and AnimationPlayer. I tried "set_frame" but Godot just says it doesn't know the Method.

CodePudding user response:

If you are following the tutorial series I think you are following (Godot Action RPG)… You are using an AnimationTree with AnimationNodeBlendSpace2D (BlendSpace2D).

The BlendSpace2D picks an animation based on an input vector "blend_position". This way you can use BlendSpace2D to pick an animation based on the direction of motion or the direction the player character is looking at. For example, you can "idle_up", "idle_down", "idle_left", and "idle_right" animations, and use BlendSpace2D to pick one in runtime based on a direction vector.

Thus, you need to set the "blend_position" of the BlendSpace2D like this:

animationTree.set("parameters/NameOfTheBlendSpàce2D/blend_position", vector)

Where:

  • animationTree is a variable set to the AnimationTree.
  • "NameOfTheBlendSpàce2D" is the name of the BlendSpace2D you want to set (e.g. "Idle").
  • vector is a Vector2D with the direction you want (e.g. Vector2.UP).

This is shown in the episode 6 of the tutorial series (Animation in all directions with an AnimationTree).


You can find a reference project by HeartBeast at arpg-reference, where you can find a function update_animation_blend_positions that looks like this:

func update_animation_blend_positions():
    animationTree.set("parameters/Idle/blend_position", input_vector)
    animationTree.set("parameters/Run/blend_position", input_vector)
    animationTree.set("parameters/Attack/blend_position", input_vector)
    animationTree.set("parameters/Roll/blend_position", input_vector)

Here "Idle", "Run", "Attack", and "Roll" are BlendSpace2D, each configured with animations for the corresponding actions, and this function updates them in sync so that they are picking the correct animation.

As far as I can tell the code from the repository is further refactored from what is show in the tutorial series. This code from the repository is under MIT licence.

  • Related