Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

2D sprite animation

Introduction

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.

Note

Art for the following examples by https://opengameart.org/users/ansimuz and tgfcoder.

Individual images with AnimatedSprite2D

Dans ce scénario, vous avez une collection d'images, qui contient toutes les images pour l'animation de votre personnage. Pour cet exemple, nous allons utiliser l'animation suivante :

../../_images/2d_animation_run_preview.gif

You can download the images here: 2d_sprite_animation_assets.zip

Décompressez les images et placez-les dans le dossier de votre projet. Configurez votre arbre de scène avec les nœuds suivants :

../../_images/2d_animation_tree1.webp

Note

Le nœud racine peut également être Area2D ou RigidBody2D. L'animation sera toujours faite de la même manière. Une fois l'animation terminée, vous pouvez attribuer une forme à CollisionShape2D. Voir Physics Introduction pour plus d'informations.

Now select the AnimatedSprite2D and in its SpriteFrames property, select "New SpriteFrames".

../../_images/2d_animation_new_spriteframes.webp

Cliquez sur la nouvelle ressource SpriteFrames et vous verrez un nouveau panneau apparaît en bas de la fenêtre de l'éditeur :

../../_images/2d_animation_spriteframes.webp

Depuis le dock situé à gauche, faites glisser les 8 images individuelles dans la partie centrale du panneau SpriteFrames. Sur le côté gauche, modifiez le nom de l'animation de "default" par "run" (courir).

../../_images/2d_animation_spriteframes_done.webp

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.

Contrôle de l'animation

Une fois l'animation terminée, vous pouvez contrôler l'animation via le code en utilisant les méthodes play() et stop(). Voici un bref exemple pour lire l'animation tant que la touche fléchée droite est maintenue enfoncée et l'arrêter lorsque vous la relâchez.

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()

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:

../../_images/2d_animation_frog_spritesheet.png

Faites un clique-droit sur l'image et choisissez "Enregistrer l'image sous" pour la télécharger, puis copiez l'image dans le dossier de votre projet.

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".

Cliquez sur la nouvelle ressource SpriteFrames. Cette fois, lorsque le panneau inférieur apparaît, sélectionnez "Add frames from a Sprite Sheet".

../../_images/2d_animation_add_from_spritesheet.webp

Il vous sera demandé d'ouvrir un fichier. Sélectionnez votre feuille de sprite.

Une nouvelle fenêtre s'ouvrira, montrant votre feuille de sprite. La première chose à faire est de modifier le nombre d'images verticales et horizontales de votre feuille de sprites. Dans cette feuille de sprites, nous avons quatre images horizontales et deux images verticales.

../../_images/2d_animation_spritesheet_select_rows.webp

Ensuite, sélectionnez les images de la feuille de sprites que vous voulez inclure dans votre animation. Nous sélectionnerons les quatre du haut, puis nous cliquerons sur "Add 4 frames" pour créer l'animation.

../../_images/2d_animation_spritesheet_selectframes.webp

Vous verrez maintenant votre animation sous la liste des animations dans le panneau du bas. Double-cliquez sur le nom par défaut pour changer le nom de l'animation de saut.

../../_images/2d_animation_spritesheet_animation.webp

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

../../_images/2d_animation_play_spritesheet_animation.webp

Feuille de Sprite avec 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.

Considérez cette feuille de sprite (sprite sheet), qui contient 6 images d'animation :

../../_images/2d_animation_player-run.png

Faites un clique-droit sur l'image et choisissez "Enregistrer l'image sous" pour télécharger, puis copiez l'image dans votre dossier de votre projet.

Notre objectif est d’afficher ces images l’une après l’autre en boucle. Commencez par configurer votre arbre de scène :

../../_images/2d_animation_tree2.webp

Note

Le nœud racine peut également être Area2D ou RigidBody2D. L'animation sera toujours faite de la même manière. Une fois l'animation terminée, vous pouvez attribuer une forme à CollisionShape2D. Voir Physics Introduction pour plus d'informations.

Faites glisser la feuille de sprite (sprite sheet) dans la propriété Texture du sprite et vous verrez toute la feuille affichée à l'écran. Pour la découper en images individuelles, développez la section Animation de l'inspecteur et réglez Hframes sur 6. Hframes et Vframes représente le nombre d'images horizontales et verticales dans votre feuille de sprite.

../../_images/2d_animation_setframes.webp

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.

Sélectionnez AnimationPlayer et cliquez sur le bouton "Animation" suivi de "Nouveau". Nommez la nouvelle animation "walk" (marche). Définissez la longueur de l'animation sur 0.6 et cliquez sur le bouton "Bouclage de l'animation" pour que notre animation se répète.

../../_images/2d_animation_new_animation.webp

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

../../_images/2d_animation_new_track.webp

Continuez à ajouter des images à chaque point de la timeline (0.1 secondes par défaut) jusqu'à ce que toutes les images soient comprises entre 0 et 5. Vous verrez les images apparaître dans la piste d'animation :

../../_images/2d_animation_full_animation.webp

Appuyez sur "Play" pour voir à quoi ressemble l'animation.

../../_images/2d_animation_running.gif

Contrôle d'une animation 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()

Note

Si la mise à jour simultanée d'une animation et d'une propriété séparée (par exemple, un platformer peut mettre à jour les propriétés h_flip/v_flip du sprite lorsqu'un personnage tourne lorsqu'il lance une animation 'tourner'), il est important de se rappeler que play() ne sera pas appliqué immédiatement. Au lieu de cela, il est appliqué la prochaine fois que le AnimationPlayer est traité. Ceci peut finir par se retrouver sur l'image suivante, provoquant un 'glitch' où le changement de propriété a été appliqué mais l'animation ne l'a pas été. Si cela s'avère être un problème, après avoir appelé play(), vous pouvez appeler advance(0) pour mettre à jour l'animation immédiatement.

Résumé

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.