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

Introducción

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

El arte de los siguientes ejemplos está hecho por https://opengameart.org/users/ansimuz y tgfcoder.

Individual images with AnimatedSprite2D

En este escenario, tienes una colección de imágenes, cada una conteniendo un frame de la animación del personaje. Para este ejemplo, usaremos la siguiente animación:

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

You can download the images here: 2d_sprite_animation_assets.zip

Descomprime las imágenes y colócalas en la carpeta de tu proyecto. Configura tu árbol de escena con los siguientes nodos:

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

Nota

El nodo raíz puede ser también Area2D o RigidBody2D. La animación se hará del mismo modo. Una vez que la animación esté completa, puedes asignar una forma al CollisionShape2D. Ver Introducción a la física para más información.

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

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

Haz clic en el nuevo recurso SpriteFrames y verás que aparece un nuevo panel en la parte inferior de la ventana del editor:

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

Desde el panel del Sistema de Archivos en el lado izquierdo, arrastra las 8 imágenes individuales a la parte central del panel de SpriteFrames. En el lado izquierdo, cambia el nombre de la animación de "default" a "run".

../../_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.

Controlando la animación

Una vez que la animación está completa, puedes controlar la animación a través del código usando los métodos play() y stop(). Aquí hay un breve ejemplo para reproducir la animación mientras se mantiene la tecla de la flecha derecha, y detenerla cuando se suelta la tecla.

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

Haz clic con el botón derecho del ratón en la imagen y selecciona "Guardar imagen como" para descargarla, luego copia la imagen en la carpeta de tu proyecto.

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

Haz clic en el nuevo recurso de SpriteFrames. Esta vez, cuando aparezca un panel en la parte inferior, selecciona "Añadir Frames desde un Sprite Sheet".

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

Se te pedirá que abras un archivo. Selecciona tu hoja de sprites.

Se abrirá una nueva ventana, mostrando tu hoja de sprites. Lo primero que tendrás que hacer es cambiar el número de imágenes verticales y horizontales en tu hoja de sprites. En esta hoja de sprites, tenemos cuatro imágenes horizontalmente y dos verticalmente.

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

A continuación, selecciona los cuadros de la hoja de sprites que quieres incluir en tu animación. Seleccionaremos los cuatro primeros, y luego haremos clic en "Añadir 4 cuadros" para crear la animación.

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

Ahora verás tu animación en la lista de animaciones en el panel inferior. Haz doble clic sobre default para cambiar el nombre de la animación a jump.

../../_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

Sprite sheet con 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.

Consideremos esta hoja de sprites, que contiene 6 cuadros de animación:

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

Haz clic con el botón derecho del ratón en la imagen y selecciona "Guardar imagen como" para descargarla, luego copia la imagen en la carpeta de tu proyecto.

Nuestro objetivo es mostrar estas imágenes una tras otra en un bucle. Comienza por establecer tu árbol de escenas:

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

Nota

El nodo raíz puede ser también Area2D o RigidBody2D. La animación se hará del mismo modo. Una vez que la animación esté completa, puedes asignar una forma al CollisionShape2D. Ver Introducción a la física para más información.

Arrastra la hoja de sprites en la propiedad Texture del Sprite, y verás toda la hoja desplegada en la pantalla. Para cortarla en cuadros individuales, expande la sección Animación en el Inspector y pon los Cuadros a "6". Hframes y Vframes son el número de marcos horizontales y verticales en tu hoja de sprites.

../../_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.

Selecciona el AnimationPlayer y haz clic en el botón Animation seguido de New. Nombra a la nueva animación "walk". Ponga la duración de la animación en "0.6" y haga clic en el botón "Loop" para que nuestra animación se repita.

../../_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

Continúa agregando cuadros en cada punto de la línea de tiempo (0,1 segundos por defecto), hasta que tengas todos los cuadros de 0 a 5. Verás los cuadros que realmente aparecen en la pista de animación:

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

Presiona "Play" en la animación para ver cómo se ve.

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

Controlando una animación de 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()

Nota

Si se actualiza tanto una animación como una propiedad separada a la vez (por ejemplo, un plataformero puede actualizar las propiedades h_flip/v_flip del sprite cuando un personaje gira al iniciar una animación 'giratoria'), es importante tener en cuenta que play() no se aplica instantáneamente. En su lugar, se aplica la próxima vez que se procese el AnimationPlayer. Esto puede terminar en el siguiente cuadro, causando un cuadro de "glitch", donde se aplicó el cambio de propiedad pero no la animación. Si esto resulta ser un problema, después de llamar a play(), puedes llamar a advance(0) para actualizar la animación inmediatamente.

Sumario

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.