Attention: Here be dragons
This is the latest
(unstable) version of this documentation, which may document features
not available in or compatible with released stable versions of Godot.
Checking the stable version of the documentation...
2D sprite animation
Introdução
In this tutorial, you'll learn how to create 2D animated characters with the AnimatedSprite2D class and the AnimationPlayer. Typically, when you create or download an animated character, it will come in one of two ways: as individual images or as a single sprite sheet containing all the animation's frames. Both can be animated in Godot with the AnimatedSprite2D class.
First, we'll use AnimatedSprite2D to animate a collection of individual images. Then we will animate a sprite sheet using this class. Finally, we will learn another way to animate a sprite sheet with AnimationPlayer and the Animation property of Sprite2D.
Nota
Art for the following examples by https://opengameart.org/users/ansimuz and tgfcoder.
Individual images with AnimatedSprite2D
Neste cenário, você tem uma coleção de imagens, cada qual contendo um dos seus frames de animação do personagem. Para este exemplo, nós usaremos a seguinte animação:

You can download the images here: 2d_sprite_animation_assets.zip
Descompacte as imagens e coloque-as na pasta do seu projeto. Configure a árvore da sua cena com os seguintes nós:

Nota
O nó raiz também pode ser Area2D ou RigidBody2D. A animação ainda será feita da mesma maneira. Assim que a animação estiver completa, você pode atribuir uma forma ao CollisionShape2D. Veja Introdução à Física para mais informação.
Now select the AnimatedSprite2D
and in its SpriteFrames property, select
"New SpriteFrames".

Clique no novo recurso SpriteFrames e você verá um novo painel aparecer na parte inferior na janela do editor:

Pelo painel de Sistema de Arquivos no lado esquerdo, arraste as 8 imagens individuais para a parte central do painel de SpriteFrames. No lado esquerdo, mude o nome da animação de "default" para "run".

Use the "Play" buttons on the top-right of the Filter Animations input to preview the animation. You should now see the animation playing in the viewport. However, it is a bit slow. To fix this, change the Speed (FPS) setting in the SpriteFrames panel to 10.
You can add additional animations by clicking the "Add Animation" button and adding additional images.
Controlando a animação
Uma vez que a animação estiver completa, você pode controlar a animação por meio do código usando os métodos play()
e stop()
. Aqui está um breve exemplo para reproduzir a animação enquanto a tecla da seta para direita está sendo pressionada, e para parar a animação quando a tecla é solta.
extends CharacterBody2D
@onready var _animated_sprite = $AnimatedSprite2D
func _process(_delta):
if Input.is_action_pressed("ui_right"):
_animated_sprite.play("run")
else:
_animated_sprite.stop()
using Godot;
public partial class Character : CharacterBody2D
{
private AnimatedSprite2D _animatedSprite;
public override void _Ready()
{
_animatedSprite = GetNode<AnimatedSprite2D>("AnimatedSprite2D");
}
public override void _Process(double delta)
{
if (Input.IsActionPressed("ui_right"))
{
_animatedSprite.Play("run");
}
else
{
_animatedSprite.Stop();
}
}
}
Sprite sheet with AnimatedSprite2D
You can also easily animate from a sprite sheet with the class AnimatedSprite2D
.
We will use this public domain sprite sheet:

Clique com o botão direito do mouse na imagem e selecione "Salvar imagem como" para baixá-la, e logo depois copie a imagem na pasta do seu projeto.
Set up your scene tree the same way you did previously when using individual images.
Select the AnimatedSprite2D
and in its SpriteFrames property, select "New SpriteFrames".
Clique no novo recurso SpriteFrames. Dessa vez, quando o painel inferior aparecer, selecione "Add frames from a Sprite Sheet(Adicionar frames de uma Sprite Sheet)".

Será pedido que você abra um arquivo. Selecione sua sprite sheet.
Uma nova janela abrirá, mostrando sua sprite sheet. A primeira coisa que você precisará fazer é mudar o número de imagens verticais e horizontais em sua sprite sheet. Nesta sprite sheet, nós temos quatro imagens horizontalmente e duas imagens verticalmente.

Em seguida, selecione os frames da sprite sheet que você quer incluir na sua animação. Nós vamos selecionar os quatro de cima, depois clique em "Add 4 frames(Adicionar 4 frame(s))" para criar a animação.

Agora você verá sua animação na lista de animações no painel inferior. Clique duas vezes em "default" para mudar o nome da animação para "jump".

Finally, check the play button on the SpriteFrames editor to see your frog jump!

Sprite sheet com AnimationPlayer
Another way that you can animate when using a sprite sheet is to use a standard Sprite2D node to display the texture, and then animating the change from texture to texture with AnimationPlayer.
Considere esta sprite sheet, a qual contém 6 quadros de animação:

Clique com o botão direito na imagem e selecione "Salvar imagem como" para baixá-la. Em seguida, copie a imagem para dentro da pasta do seu projeto.
Nosso objetivo é exibir essas imagens uma após a outra em um ciclo. Começe configurando a árvore da sua cena:

Nota
O nó raiz também pode ser Area2D ou RigidBody2D. A animação ainda será feita da mesma maneira. Assim que a animação estiver completa, você pode atribuir uma forma ao CollisionShape2D. Veja Introdução à Física para mais informação.
Arraste a sprite sheet para a propriedade Texture da Sprite, e você verá toda a folha exibida na tela. Para cortá-la em frames individuais, expanda a seção Animação no Inspetor e defina a propriedade Hframes como 6
. Hframes e Vframes são o número de quadros horizontais e verticais, respectivamente na sua sprite sheet.

Now try changing the value of the Frame property. You'll see that it ranges
from 0
to 5
and the image displayed by the Sprite2D changes accordingly.
This is the property we'll be animating.
Selecione o AnimationPlayer
e clique no botão "Animação" e ,depois, em "Novo". Nomeie a nova animação como "walk". Defina a duração da animação como 0.6
e clique no botão "Loop" para que a nossa animação se repita.

Now select the Sprite2D
node and click the key icon to add a new track.

Continue adicionando frames a cada ponto da linha do tempo (0.1
segundos por padrão), até que você tenha todos os frames de 0 a 5. Você verá os frames realmente aparecendo na trilha de animação:

Pressione "Play" na animação para ver como ela fica.

Controlando uma animação do AnimationPlayer
Like with AnimatedSprite2D, you can control the animation via code using
the play()
and stop()
methods. Again, here is an example to play the
animation while the right arrow key is held, and stop it when the key is
released.
extends CharacterBody2D
@onready var _animation_player = $AnimationPlayer
func _process(_delta):
if Input.is_action_pressed("ui_right"):
_animation_player.play("walk")
else:
_animation_player.stop()
using Godot;
public partial class Character : CharacterBody2D
{
private AnimationPlayer _animationPlayer;
public override void _Ready()
{
_animationPlayer = GetNode<AnimationPlayer>("AnimationPlayer");
}
public override void _Process(double delta)
{
if (Input.IsActionPressed("ui_right"))
{
_animationPlayer.Play("walk");
}
else
{
_animationPlayer.Stop();
}
}
}
Nota
If updating both an animation and a separate property at once
(for example, a platformer may update the sprite's h_flip
/v_flip
properties when a character turns while starting a 'turning' animation),
it's important to keep in mind that play()
isn't applied instantly.
Instead, it's applied the next time the AnimationPlayer is processed.
This may end up being on the next frame, causing a 'glitch' frame,
where the property change was applied, but the animation was not.
If this turns out to be a problem, after calling play()
, you can call advance(0)
to update the animation immediately.
Resumo
These examples illustrate the two classes you can use in Godot for 2D animation.
AnimationPlayer
is a bit more complex than AnimatedSprite2D
,
but it provides additional functionality, since you can also
animate other properties like position or scale.
The class AnimationPlayer
can also be used with an AnimatedSprite2D
.
Experiment to see what works best for your needs.