What You’ll Learn in This Hour:
Becoming familiar with the animation editor
Creating and saving a new animation
What keyframes are, how they work, and how to create them
Calling animations from GDScript
Calling GDScript from within an animation
Blending two animations together
Smooth transitioning between subsequent animations
Animation is a key aspect in most games. It’s used to simulate running, jumping, grabbing, shooting, and many more actions that happen over
time. Even when a character is standing still, it’s often given an idle animation, in which it moves up and down to give the impression that the
player is breathing.
In this hour, you’ll learn how to use the animation editor, how to create animations, how to assign them to sprites, and how to control them with
code.
Animation Editor
The animation editor, as the name suggests, is where you create and edit your animations. Every animation starts here.
Opening the Editor
To open the animation editor, click on the word Animation at the bottom of the window (Figure 10.1). It should open a new pane, which looks
like Figure 10.1.
FIGURE 10.1
The animation editor window.
As you can see, the editor is blank and all the buttons are grayed out. You can’t create an animation out of the blue or assign animations to
random nodes. Instead, every animation needs to be assigned to a node called the AnimationPlayer.
The AnimationPlayer Node
There are two things you need to remember about this node:
It can play any animation you give it.
It can only play one animation at a time.
For example, you have many enemy monsters crawling around your game. They are all playing their own “crawling” animation simultaneously
and therefore each of them needs their own AnimationPlayer node as a child.
On the other hand, you can create one global AnimationPlayer node that plays all singular animations, such as fade-to-black scene
transitions or shaking the screen.
So, create a Sprite and attach an AnimationPlayer node to it. Once you select the AnimationPlayer node, the animation editor should light
up and give you some options (Figure 10.2).
FIGURE 10.2
The (very simple) node setup used for animations.
Creating a New Animation
To create a new animation, click the
New Animation button. It will open a dialog asking you for the animation name (Figure 10.3).
FIGURE 10.3
The New Animation dialog. Replace “New Anim” with the name you want to give your animation.
After entering your desired name and clicking OK, you’ll have even more options. Don’t worry, we will explore most of them in the upcoming
chapters when we will actually create an animation.
111111111
22222222Saving and Loading Animations
Once you’ve created an animation, it’s important to save it. The first reason is, obviously, that you don’t want to lose your hard work. The
second reason is saving the animation in a file allows you to use this same animation multiple times in other places.
For example, every monster in your game might use the same “crawling” animation. It would be tedious to recreate it for each and every one of
them. Save it in a file and reload it in the other AnimationPlayers.
To save an animation, press the
Save Animation button. The first time you do so, it will ask you where you want to save it and under
which name.
NOTE
Why Save It Under a Different Name?
There’s an important distinction between the name of the animation and the name of the file that contains the animation.
The name of the animation is used to call the animation from code. So, say your running animation is called “Run,” you would use that name to
play it from code.
The name of the file is merely useful for you, the animator, to easily find animations in your FileSystem. For example, you might use a different
naming convention for these files, such as “RunningMonster” or “Run-Version1.” In an ideal situation, the programmer should never need to
bother with the file names. It improves workflow to keep the programmer’s tasks separate from those of other people in the team.
To load an animation (that you previously saved), press the
Open Animation button. Locate the animation file and open it.
On the Concept of Animation
Generally, people distinguish between two types of animation: spritesheet and keyframe.
Spritesheet animation is the “old school” way of animating. You might remember those old flipbooks where you have hundreds of pages with
drawings, each only slightly different from the previous one. If you look at the pictures one-by-one, they seem like a bunch of similar pictures. If
you flip through them with your finger, though, your eyes see it as an animation and the drawings seem to come to life.
Spritesheet animation does this. You create multiple drawings of your character in (slightly) different positions, and put them in a single image,
which is called a spritesheet. Then, you tell the game to “play frame 2, 3, 4, and 5 really fast,” and it suddenly looks as if the character is moving
(Figure 10.4).
FIGURE 10.4
A spritesheet that shows the start of a running animation. (Or, if we’re very mean to our player, a jumping off a building animation.)
Keyframe animation is what’s most often used these days. Instead of drawing every single frame yourself, you only set the most important
(“key”) frames. The software then interpolates between those positions, automatically creating movement (see Figure 10.5).
FIGURE 10.5
The same animation, but with keyframes. We only need to set two keyframes at the “extreme positions”, and the animation player does the
rest. Note in this case, we’d need separate keyframes for the other arm and both the legs. (Those weren’t shown in the image for clarity
purposes.)
InGodot, the keyframe system is used, because it can be used for both 2D and 3D, and it’s more powerful. The next chapters explain the
keyframe system.
NOTE
But What If I Really Want Spritesheet Animation?
There’s a special node for that: the AnimatedSprite node. It won’t be discussed further, as it’s beyond the scope of this chapter.
Alternatively, you can achieve spritesheet animation with keyframes as well! (That’s how useful they are.) All you need to do is make every
single frame of the spritesheet a separate keyframe.
Timeline and Keyframes
A large part of the animation editor is dedicated to the so-called Timeline. That’s a good thing, because it’s by far the most important element.
The timeline contains what happens at every step of the animation (Figure 10.6).
FIGURE 10.6
The timeline, with a few tracks on it. (Tracks are explained in a bit.)
Animation Duration
At the bottom of the animation editor (Figure 10.7), you’ll find all the controls for animation length and view.
111111111
22222222FIGURE 10.7
The toolbar for controlling animation length and how fine-grained your control is.
First, let’s set the length of the animation. To do so, edit the Length property, which is in seconds. Then, it’s important to set the Step property.
You might think that you can just place keyframes anywhere in your animation, but that’s not true. Think about it. If you could place a keyframe
anywhere, you’d soon run into precision errors. One keyframe could be a few milliseconds off and you wouldn’t notice.
Godot, therefore, automatically divides the whole animation into steps. The default setting is 0.1, which means every tenth of a second you can
place a keyframe. This ensures all keyframes within the same step line up perfectly. If you want more fine-grained control, you can lower this
number.
The slider on the left is used for zooming in and out of the view. It doesn’t actually change the length of the animation, but rather how much of it
you can see. If you zoom in more, you can see the step lines.
Lastly, if the
Loop Button is toggled on, the animation loops. This means that, when the animation reaches its end, it automatically jumps
to the beginning and starts again.
NOTE
Nothing Is Fixed
You can always edit all properties of the animation later. If it turns out you need a longer animation, just update the length. In the next
paragraphs, when you learn about keyframes, you’ll also see you can move them around and change everything on the fly.
Creating Tracks and Keyframes
Now comes the best part! InGodot, everything can be keyframed: all of the properties of all of the nodes in the scene tree, as well as their
resources. So, if you select our Sprite, its properties suddenly look like Figure 10.8.
FIGURE 10.8
What the inspector looks like with the Animation window open. Notice the keyframe symbol behind every property.
To create a keyframe, simply click on the
Keyframe symbol behind the property you want animated. If it’s the first keyframe, Godot will
ask you if you want to create a new track. This is merely a confirmation dialog—you always need a track for every animated property. In this
case, we’ll keyframe the rotation property (see Figure 10.9).
FIGURE 10.9
Track confirmation dialog.
Once a track is created, clicking on the
Keyframe symbol creates a keyframe on the existing track. Alternatively, you can press the
Insert key to create a keyframe.
Modifying Keyframes
Keyframes are always placed at the position of the cursor in the timeline. The cursor is the vertical blue line. So, before you create a keyframe,
always check if the cursor is at the right time. If not, you might accidentally override previous keyframes. To move the cursor, click on the top
part of the timeline (see Figure 10.10).
FIGURE 10.10
Click somewhere on this box and the timeline cursor jumps to the position you clicked.
To move a keyframe around (after you’ve created it), click and drag it horizontally within the same track.
To have closer control, select a keyframe (by clicking on it) and click the
Edit Keyframe button (at the bottom right). This opens a small
pane where you can precisely set the Time and the Value (Figure 10.11).
FIGURE 10.11
Pane for precise keyframe editing. This keyframe is located at 0 seconds within the animation and sets the rotation of the Sprite to 0 degrees.
Of course, animations are only interesting if there are multiple keyframes. So, we go ahead and create another keyframe for the Sprite. We
move the timeline cursor to 0.5s, rotate the Sprite 180 degrees, and click the keyframe symbol again. Our track now looks like Figure 10.12.
111111111
22222222FIGURE 10.12
A simple animation that smoothly rotates our Sprite upside down.
Testing the Animation
Now that we have the animation, we obviously want to run it and see how marvelous it looks. For this, we use the symbols in the top left corner
(see Figure 10.13).
FIGURE 10.13
Controls for animation playback.
You’re probably already familiar with these symbols. To play the animation from the start, use the
Rewind & Play Button. To play the
animation from where the cursor currently is, use the
Play Button. To pause playback, use the
Stop Button.
The counter on the right shows the current step of the animation. You can use the up/down arrows to jump from step to step and see the
animation in great detail.
Transform Animation
Even though everything can be keyframed, there’s one thing that’s almost always animated: one of the three transform properties (location,
rotation, and scale). Luckily, Godot has an even quicker method for animating these (see Figure 10.14). At the top of the scene view, you’ll find
three words and a
Keyframe symbol.
FIGURE 10.14
Buttons for quick transform keyframing.
By clicking on them, you can turn the words “loc”, “rot”, and “scl” green. Once you click the
Keyframe symbol, all the properties that are
green automatically get keyframed. So, in figure 10.14, location and rotation receive a keyframe, but scale does not.
Try It Yourself
Now it’s time for you to create your own amazing animation with everything you’ve learned.
TRY IT YOURSELF
ABouncing Character
In this Try It Yourself, we’ll create a character that bounces up and down.
1. Create a Sprite node, pick any image you want, and attach an AnimationPlayer.
2. Open the Animation window and create a new animation. Call it whatever you want, such as bounce or jumping.
3. Save it within your project. The name for the animation file doesn’t have to be the same as the animation name.
4. Make sure the Animation window is open and the timeline cursor is at 0 seconds.
5. Select the Sprite and go to its Transformproperties.
6. Click the Keyframe symbol to create the first keyframe. When asked to create a track, confirm.
7. Now move the timeline cursor to 0.5 seconds and move the Sprite upwards (to a lower y-coordinate).
8. Click the Keyframe symbol again and a second dot should appear on the animation track.
9. Now move the timeline cursor to 1.0 seconds and move the Sprite downward again to its original position.
10. Click the KeyFrame symbol one last time and a third dot should appear.
11. Play the animation and your character should move up and down.
12. Do not forget to save your animation after you’ve changed it.
13. BONUS: See if you can keyframe the scale property as well, so that the sprite “squishes” when it hits the ground and “elongates”
when it’s in the air (for that cartoony feel).
Easing Functions
With the last Try It Yourself, you may have noticed something. Your Sprite moves up and down, but it doesn’t really feel like a bounce, because
it moves in a linear fashion. When a real person jumps, he starts very fast, but gradually slows down as he gets higher and higher. (And,
conversely, when that person falls down, he starts falling faster and faster until he hits the ground.)
How the animation interpolates between keyframes (Figure 10.15), is decided by an easing function. For example, a linear animation—which
is the default—is the result of a linear easing function, which is a straight diagonal line.
111111111
22222222FIGURE 10.15
Buttons controlling interpolation of keyframes.
In case you’ve been wondering that’s what the buttons at the right side of every track represent.
The
Add Keyframe button provides a quick way to add another keyframe to this specific track.
The second button toggles between continuous easing (in which it uses the easing function) and discrete easing (in which it completely
abandons the easing function, and simply jumps from keyframe to keyframe).
The third button is the overall easing function. Within the editor, you can only choose linear and cubic (which is curved and the one you need
to get a realistic bounce). WithGDScript, you can set more easing functions.
The last button toggles easing on loop. When set to wrap loop interpolation, it interpolates between the last and the first keyframe as well
(which is what you often want, if your animation loops).
Try It Yourself
In Hour 7, “Handling Input,” you learned how to handle input. We’ll use that knowledge now to play an animation whenever the user presses a
certain key.
TRY IT YOURSELF
ABouncing Character—Again
In this Try It Yourself, we’ll use the bouncing animation we made earlier. When the user presses the up arrow key, our Sprite should jump
and bounce.
1. Add a script to the Sprite node.
2. Check if your AnimationPlayer still has the previously created bounce _animation. If not, you can test your skills now by
recreating it.
3. Within the script, check for input with the func _input(event): function
4. Write an if statement to check whether a key was pressed, which is done with if event is InputEventKey
5. Write an if statement that checks whether the up arrow is pressed, which is done with if event.scancode == KEY_UP:
6. OPTIONAL: Now, the event will fire as long as the up arrow
is pressed down. If you only want to play the animation when the user
releases the up-arrow, add an additional check with && event.pressed == false
7. Within the if block, tell the animation to play with $AnimationPlayer.play(“bounce”)
8. Save it and test it.
Scripting Animations
So, let’s say you’ve made an animation called “run” and it’s loaded into the AnimationPlayer. Eager to try out your new animation, you start
your game—and nothing happens. That’s because we haven’t told Godot which animation we want to play and when.
If you have a very simple setup, Autoplay can help you out. By clicking the
Autoplay button on a certain animation, it automatically
plays when the AnimationPlayer node is added to the game (which is, in this case, when the game starts). Because the AnimationPlayer
can only play a single animation at a time, you can only have one animation set to Autoplay.
Most games, however, need something way more complex. They need to dynamically call animations from a script (Listing 10.1). The following
is a script that should be placed on the Sprite and plays the animation called “run.”
LISTING10.1 Simple Animation Call
Click here to view code image
extends Sprite
func _ready():
$AnimationPlayer.play(“run”)
The next thing you want to be able to do is stop and pause the current animation (Listing 10.2).
LISTING10.2 Stopping and Pausing
Click here to view code image
$AnimationPlayer.stop() # this stops the animation, and resets it to the beginning
$AnimationPlayer.stop(false) # this merely pauses the animation
OK, so we have a run animation we can play and stop. It is tempting to write a function that checks whether a certain key is pressed (say, the
left arrow key), and if true, it plays the animation. This will most likely result in horror and confusion. Why? Because, every time you call
play(), it plays the animation again from the beginning. So, calling it every frame results in the animation getting stuck in the first few
milliseconds.
111111111
22222222To work around that, you could check whether the animation is already playing, like what is shown in Listing 10.3.
LISTING10.3 Checking the Current Animation
Click here to view code image
if $AnimationPlayer.is_playing() && $AnimationPlayer.get_current_animation() == “run”:
# do nothing, it’s already playing
else
$AnimationPlayer.play(“run”)
Animation Signals
As with all nodes, the AnimationPlayer emits signals. These are extremely useful. Even though they can be replicated with some code, it’s
recommend to use signals. Why? For example, your character has a “wood chopping” animation. Every time that animation ends, you want the
tree he’s chopping to release one wood Sprite. Then you can use a signal (Listing 10.4).
LISTING10.4 The AnimationPlayer Signals
Click here to view code image
animation_changed(old_name, new_name)
# fires whenever the animation changes. The old animation is given by
old_name, the new one by new_name
animation_finished(anim_name)
# fires whenever the current animation finishes (anim_name holds the name
of the current animation)
animation_started(anim_name)
# fires whenever a new animation starts (anim_name holds the name
of the current animation)
If you want even better control, you can, in a sense, create your own signals. Thus far, we’ve added tracks that can keyframe certain properties.
We’ve done that by clicking the
Keyframe symbol behind the desired property.
There is one extra type of track, though, we haven’t seen yet, which must be created in a different way. It’s the Call Func track. To create it,
press the
Add Track button (lower right of the animation editor), and choose Call Func.
A new window opens, asking you which node you want to attach it to. C
h
oose the Sprite.
As the name suggests, this type of track calls a function. For example, we want to call the function wood_chop() halfway through an
animation. These are the steps we should take:
1. First place the timeline cursor at 0.5s.
2. Then, press the
Add Keyframe button on the Call Func track.
3. Select the new keyframe you created and press the
Edit Keyframe button.
4. Type wood_chop in the Name field.
5. Add the function wood_chop() to the script on the Sprite, like what is shown in Listing 10.5.
LISTING10.5 Receiving the Call fromthe Call Func Track
Click here to view code image
func wood_chop():
print(“It works! Choppie choppie.”)
Blending and Transitioning Animations
With keyframes and the AnimationPlayer node, we can already make many powerful animations. There are, however, two “problems” left: we
can only play a single animation at a time and the transition from one animation to the next is very harsh—it just suddenly jumps from one
animation to the start of the next.
The first problem can be solved with blending. The second problem can be solved with adding a transition. Both of these can be
accomplished with the special AnimationTreePlayer node.
The Setup
First, do the same thing as always: add the Sprite (or whatever node you want animated) and attach an AnimationPlayer node. Next, attach
an additional AnimationTreePlayer node (Figure 10.16).
FIGURE 10.16
How to setup your Sprite to use an AnimationTreePlayer.
Go to the properties of this new node and set the Master Player to the AnimationPlayer node also attached to the Sprite. This means the
111111111
22222222animation tree we’re about to create will use animations from that specific player.
Animation Tree Editor
With the AnimationTreePlayer node selected, an additional pane has appeared next to the animation editor. This animation tree editor
should look like Figure 10.17.
FIGURE 10.17
An empty animation tree.
You might notice that it looks familiar to the visual scripting language Godot has and that’s because it is. Using the
Add Node button,
you can add any type of node to the tree. Once added, you can connect nodes by clicking and dragging from the output of one node to the input
of another.
As you can see, now the animation tree is invalid. Eventually, all nodes should lead to this “Output” node, and when that happens (correctly), it
tells you the animation tree is valid.
With the
Play Tree button, you can activate the animation tree. You can also activate/deactivate them withinGDScript, using the
set_active() function.
NOTE
Animation Trees “Replace” Animation Players
When an animation tree is not active, it has no influence at all on the game. When the animation tree is active, it overrides anything the
AnimationPlayer node is trying to do. Therefore, if you decide to use an animation tree for your character, you’ll most likely need to include all
your animations in the tree (idle, run, jump, fall, walk, and so on).
Blending Animations
Let’s say we have an animation “MoveLeft” (in which our Sprite moves to the left), and an animation “MoveUp” (in which our Sprite moves up).
Now we want to blend these two together, so that the character moves diagonally upwards instead.
To do so, add both the animations to the animation tree (using the Animation node) and add a Blend2 node. The final tree should look like
Figure 10.18.
FIGURE 10.18
An animation tree that blends two animations.
As you might expect, the Blend3 and Blend4 nodes blend 3 and 4 animations, respectively.
On the Blend2 node, you can press edit to get a slider. This slider determines how much of each animation is used. So, in our case, we want
to set it to the halfway point, to use 50 percent of the first animation, and 50 percent of the other.
That’s all you need to do! Activate the tree and the Sprite should move diagonally. Play around with the blending slider if you want to see the
effect.
Creating Transitions
Say our Sprite is moving to the left, but halfway through the animation, we want it to go upwards instead. If we switch the animation with code, it
would look horrible. Why? Because it would immediately switch to the “MoveUp” animation, instead of gradually easing into it. We can fix that
by adding a Transition node to the animation tree.
Once added, you’ll see the Transition node has only one input. To add another input, right-click on the node, and choose Add Input.
Now, remove the Blend2 node. We can’t blend two animations together and perform a transition, because both animations are already
playing. Connect the animation nodes to the transition node and it should look like Figure 10.19.
FIGURE 10.19
An animation tree that transitions between two animations.
Again, by clicking on edit on the Transition node, you can set some properties. The most important is the X-fade time. This determines how
much time it takes to transition from one animation to the next. If you set it to 0.1s, then both animations will blend for a tenth of a second and
afterward the new animation is the only one playing.
As mentioned before, the AnimationTreePlayer node replaces the AnimationPlayer node. Therefore, if you want to transition from the 0
animation to the 1 animation, you need to do so with the following lines of code in Listing 10.6.
LISTING10.6 Changing the Animation Tree
Click here to view code image
111111111
22222222$AnimationTreePlayer.transition_node_set_current(“transition”, 1)
# the first parameter is the
because you can have multiple transition nodes with different names
Summary
In this hour, you’ve learned where to find the animation editor and how to use it. You’ve learned how to create animations, save them, and open
them in an AnimationPlayer. You’ve learned how to animate anything by creating keyframes. You’ve learned how to manipulate animations
from code and how to call code from within the animation. Finally, you’ve learned how to create seamless transitions between animations
playing right after one another.
Q&A
Q. Is there a limit to the amount of AnimationPlayers, animations, tracks, or keyframes?
A. No, though it’s always recommended to keep them to a minimum. Animations are often the culprit when it comes to lagging games or
weak performance. If unsure, press the
Animation Tools button and choose Clean-Up Animation.
Q. Animating every single body part of the character is tedious. Is there no better way for such complex animations?
A. Why yes, there is. It’s called Inverse Kinematics, and can be found under Edit > Skeleton
through the character and, by moving a certain body part, the rest naturally follows along. It’s way too complicated to explain here, but be
sure to give it a try if you’re into complex and realistic character animations.
Q. Can I delete tracks?
A. Yes, simply select the track and press the
Delete Track button (in the lower right corner). In fact, there’s also a
Delete button
at the top, which deletes the whole current animation.
Q. Can I rename animations?
A. Yes. Press the
Rename button (top toolbar) and enter the new name in the dialog.
Workshop
Now that you have finished the hour, take a few moments to review and see if you can answer the following questions.
Quiz
1. True or False: you do not always need an AnimationPlayer node to play animations.
2. True or False: a single AnimationPlayer node can play as many animations as you want.
3. Pressing the key adds a new keyframe for the currently selected node.
4. True or False: you can place keyframes anywhere on the timeline.
5. True or False: you can switch the current animation withGDScript.
6. True or False: you cannot perform code within an animation.
7. To blend two animations, one needs a node, with the master player property set to a node.
Answers
1. False, you always need one.
2. False, it can only play one at a time.
3. Insert
4. True; the step in the editor acts as a helper, but you can use any float value for your keyframe’s time.
5. True, use the play(“anim_name”) function.
6. False, a Call Func track can call any function within a script.
7. AnimationTreePlayer, AnimationPlayer
Exercises
Exercise: We’ve learned a lot this hour, so this exercise touches on many different key points. We will create a monster/security
guard/whatever that patrols an area, and makes a backflip when he changes direction.
1. Create a Sprite and add a script.
2. Create two animations: MoveLeft (which moves 200 pixels to the left), and MoveRight (which moves 200 pixels to the right).
3. Within the MoveLeft animation, the Sprite should rotate 90 degrees to the left. Within the MoveRight animation, the Sprite should
111111111
22222222rotate 90 degrees to the right. (Or try something else, you want to visually see the Sprite facing either left or right. There should be a
distinction.)
4. At the end of the MoveLeft animation, call the function finished_move_left(). At the end of the MoveRight animation, call the
function finished_move_right().
5. Create an animation tree. Connect the two animations to a transition node and set a certain x-fade time (though not too long). Activate
the animation tree.
6. Within the script, use the two functions you’ve created to transition to the other animation. (So, when the MoveLeft animation is finished,
start MoveRight, and vice versa.)
7. Create an input handler (in the same script), which checks if the user presses the up arrow key. If so, change the x-fade time to a random
value, using transition_node_set_xfade_time(“name”, newtime)
Bonus Exercise: I’ve mentioned the differences between spritesheet animation and keyframe animation. Now that you know all about
animations, try to create a spritesheet animation using keyframes.
1. Find any spritesheet you like.
2. Create a Sprite, and set the spritesheet as the image of the Sprite.
3. Within the Sprite properties window, you should find two properties called Vframes (vertical frames) and Hframes (horizontal frames).
These “cut” the spritesheet into frames for you. For example, if a spritesheet has 6 frames arranged in 2 rows and 3 columns, you should
set Vframes to 2 and Hframes to 3.
4. Find the frame property of the Sprite, and keyframe it.
5. Move the timeline cursor a bit, change the frame to the next number and keyframe it again.
6. Repeat the last step until you’ve used up all the frames.
7. Play the animation and enjoy life.
111111111
22222222