Up to date

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

Вступ до функцій анімації

Вузол :ref:`class_AnimationPlayer`дозволяє створювати будь-яку просту, чи складну, анімацію.

З цього посібника ви дізнаєтеся про:

  • Роботу з панеллю Анімації

  • Анімацію будь-якої властивості будь-якого вузла

  • Створення простої анімації

In Godot, you can animate anything available in the Inspector, such as Node transforms, sprites, UI elements, particles, visibility and color of materials, and so on. You can also modify values of script variables and even call functions.

Створення вузла AnimationPlayer (Відтворювач Анімації)

Щоб використовувати інструменти анімації, спочатку потрібно створити вузол AnimationPlayer.

The AnimationPlayer node type is the data container for your animations. One AnimationPlayer node can hold multiple animations, which can automatically transition to one another.

Вузол AnimationPlayer

Вузол AnimationPlayer

After you create an AnimationPlayer node, click on it to open the Animation Panel at the bottom of the viewport.

Розташування панелі анімації

Розташування панелі анімації

The animation panel consists of four parts:

Панель анімації

Панель анімації

  • Елементи керування анімацією (наприклад, додавання, завантаження, збереження та видалення анімацій)

  • Список доріжок (треків)

  • Шкала часу з ключовими кадрами

  • The timeline and track controls, where you can zoom the timeline and edit tracks, for example.

Комп'ютерна анімація опирається на ключові кадри

A keyframe defines the value of a property at a point in time.

Diamond shapes represent keyframes in the timeline. A line between two keyframes indicates that the value doesn't change between them.

Ключові кадри в Godot

Ключові кадри в Godot

You set values of a node's properties and create animation keyframes for them. When the animation runs, the engine will interpolate the values between the keyframes, resulting in them gradually changing over time.

Два ключових кадри - це все, що потрібно для отримання плавного руху

Два ключових кадри - це все, що потрібно для отримання плавного руху

The timeline defines how long the animation will take. You can insert keyframes at various points, and change their timing.

Шкала часу на панелі анімації

Шкала часу на панелі анімації

Each line in the Animation Panel is an animation track that references a Normal or Transform property of a node. Each track stores a path to a node and its affected property. For example, the position track in the illustration refers to the position property of the Sprite2D node.

Зразок Звичайних анімаційних доріжок

Зразок Звичайних анімаційних доріжок

Порада

If you animate the wrong property, you can edit a track's path at any time by double-clicking on it and typing the new path. Play the animation using the "Play from beginning" button Грати з початку (or pressing Shift + D on keyboard) to see the changes instantly.

Урок: Створення простої анімації

Налаштування сцени

Для цього уроку ми створимо вузол Sprite і дамо йому в нащадки AnimationPlayer. Ми анімуємо переміщення спрайту між двома точками на екрані.

Налаштування нашої сцени

Налаштування нашої сцени

Попередження

AnimationPlayer inherits from Node instead of Node2D or Node3D, which means that the child nodes will not inherit the transform from the parent nodes due to a bare Node being present in the hierarchy.

Тому не рекомендується додавати вузлу AnimationPlayer в нащадки вузли, які мають 2D/3D перетворення.

The sprite holds an image texture. For this tutorial, select the Sprite2D node, click Texture in the Inspector, and then click Load. Select the default Godot icon for the sprite's texture.

Adding an animation

Select the AnimationPlayer node and click the "Animation" button in the animation editor. From the list, select "New" (Додати анімацію) to add a new animation. Enter a name for the animation in the dialog box.

Додавання нової анімації

Додавання нової анімації

Manage an animation libraries

For reusability, the animation is registered in a list in the animation library resource. If you add an animation to AnimationPlayer without specifying any particular settings, the animation will be registered in the [Global] animation library that AnimationPlayer has by default.

Manage animations

Manage animations

If there are multiple animation libraries and you try to add an animation, a dialog box will appear with options.

Add a new animation with library option

Add a new animation with library option

Додавання доріжки

To add a new track for our sprite, select it and take a look at the toolbar:

Зручні кнопки

Зручні кнопки

These switches and buttons allow you to add keyframes for the selected node's location, rotation, and scale. Since we are only animating the sprite's position, make sure that only the location switch is selected. The selected switches are blue.

Click on the key button to create the first keyframe. Since we don't have a track set up for the Position property yet, Godot will offer to create it for us. Click Create.

Godot will create a new track and insert our first keyframe at the beginning of the timeline:

Доріжка спрайта

Доріжка спрайта

Другий ключовий кадр

We need to set our sprite's end location and how long it will take for it to get there.

Let's say we want it to take two seconds to move between the points. By default, the animation is set to last only one second, so change the animation length to 2 in the controls on the right side of the animation panel's timeline header.

Тривалість анімації

Тривалість анімації

Now, move the sprite right, to its final position. You can use the Move tool in the toolbar or set the Position's X value in the Inspector.

Click on the timeline header near the two-second mark in the animation panel and then click the key button in the toolbar to create the second keyframe.

Запуск анімації

Натисніть на кнопку "Грати з початку" (Грати з початку).

Вау! Наша анімація працює:

Анімація

Анімація

Туди-сюди

Godot has an interesting feature that we can use in animations. When Animation Looping is set but there's no keyframe specified at the end of the animation, the first keyframe is also the last.

This means we can extend the animation length to four seconds now, and Godot will also calculate the frames from the last keyframe to the first, moving our sprite back and forth.

Циклічність анімації

Циклічність анімації

You can change this behavior by changing the track's loop mode. This is covered in the next chapter.

Параметри доріжки

Each track has a settings panel at the end, where you can set its update mode, track interpolation, and loop mode.

Параметри доріжки

Параметри доріжки

Режим оновлення доріжки повідомляє Godot, коли оновлювати значення властивостей. Він може бути:

  • Неперервний: Оновлювати властивість на кожному кадрі

  • Дискретно: Оновлювати властивість лише на ключових кадрах

  • Capture: if the first keyframe's time is greater than 0.0, the current value of the property will be remembered and will be blended with the first animation key. For example, you could use the Capture mode to move a node that's located anywhere to a specific location.

Режими доріжки

Режими доріжки

You will usually use "Continuous" mode. The other types are used to script complex animations.

Track interpolation tells Godot how to calculate the frame values between keyframes. These interpolation modes are supported:

  • Найближчий: встановлює найближче значення ключового кадру

  • Лінійний: Встановлює значення на основі обчислення лінійної функції між двома ключовими кадрами

  • Кубічний: Встановлює значення на основі обчислення кубічної функції між двома ключовими кадрами

  • Linear Angle (Only appears in rotation property): Linear mode with shortest path rotation

  • Cubic Angle (Only appears in rotation property): Cubic mode with shortest path rotation

Режими інтерполяції

Режими інтерполяції

With Cubic interpolation, animation is slower at keyframes and faster between them, which leads to more natural movement. Cubic interpolation is commonly used for character animation. Linear interpolation animates changes at a fixed pace, resulting in a more robotic effect.

Godot supports two loop modes, which affect the animation when it's set to loop:

Режими циклу

Режими циклу

  • Затиснута інтерполяція циклу: Коли вибрано цей режим, анімація зупиняється після останнього ключового кадру цієї доріжки. Коли перший ключовий кадр буде досягнутий знову, анімація скинеться до своїх початкових значень.

  • Загорнута інтерполяція циклу: Коли вибрано цей режим, Godot обчислює анімацію після останнього ключового кадру, повертаючись значень першого ключового кадру.

Ключові кадри для інших властивостей

Godot's animation system isn't restricted to position, rotation, and scale. You can animate any property.

If you select your sprite while the animation panel is visible, Godot will display a small keyframe button in the Inspector for each of the sprite's properties. Click on one of these buttons to add a track and keyframe to the current animation.

Ключові кадри для інших властивостей

Ключові кадри для інших властивостей

Редагування ключових кадрів

You can click on a keyframe in the animation timeline to display and edit its value in the Inspector.

Редактор ключових кадрів

Редактор ключових кадрів

You can also edit the easing value for a keyframe here by clicking and dragging its easing curve. This tells Godot how to interpolate the animated property when it reaches this keyframe.

Ви можете налаштовувати анімацію таким чином, поки рух не стане "правильним."

Використання доріжок RESET

Ви можете налаштувати спеціальну анімацію RESET, щоб містити "позу за замовчуванням". Вона використовується для відновлення пози за замовчуванням під час збереження сцени та повторного відкриття її в редакторі.

Для наявних доріжок можна додати анімацію під назвою "RESET" (з урахуванням регістру), а потім додати доріжки для кожної властивості, яку потрібно оновити. Єдиний ключовий кадр повинен бути на часі 0, і містити потрібне значення за замовчуванням для кожної доріжки.

Якщо властивість Reset On Save (Скинути при зберіганні") AnimationPlayer увімкнена, сцена буде збережена зі скинутими застосованими ефектами анімації (ніби її вернули до часу 0.0). Це впливає лише на збережений файл – доріжки властивостей у редакторі залишаються там, де вони були.

If you want to reset the tracks in the editor, select the AnimationPlayer node, open the Animation bottom panel then choose Apply Reset in the animation editor's Edit dropdown menu.

Під час додавання доріжок до нових анімацій редактор попросить вас автоматично створити доріжку RESET під час використання значка ключового кадру поруч із властивістю в інспекторі. Це не застосовується до доріжок, створених за версіями Godot до 3.4, оскільки функція відстеження скидання анімації була додана в 3.4.

Примітка

RESET tracks is also used as a reference value for blending. See also For better blending.