In this tutorial we are going to look at Sprite Animation in Godot Engine, specifically on using the AnimatedSprite class. We are going to import and create a node that has multiple frames of animation, then look at some code to flip between frames. In the immediately following tutorial, we will then cover a much better animation method using AnimationPlayer.
As always, there is an HD Video version of this tutorial available right here or embedded below.
Alright, let’s just right in with AnimatedSprite.
AnimatedSprite is a handy Node2D derived class that enables you to have a node with multiple SpriteFrames. In plain English, this class enables us to have a sprite with multiple frames of animation.
Speaking of frames of animation, this is the sequence of png images I am going to use for this example:
You can download the zip file containing these images here, or of course you can use whatever images you want.
Now we simply want to import them to our using the standard Import->2D Texture method. Be aware, you can multi select in the Importer, so you can import the entire sequence in one go. Assuming you’ve done it right, your FileSystem should look somewhat like:
Now add an AnimatedSprite node to your scene like so:
Now we add the frames to our AnimatedSprite by selecting Frame->New SpriteFrames
Now drop it down again and select Edit:
The 2D editor will now be replaced with the SpriteFrames editor. Click the open icon:
Shift select all of the sprite frames and select OK
All of your sprites should now appear in the editor:
Now let’s add some code to flip through the frames of our AnimatedSprite. Attach a script to the AnimatedSprite node, then use the following code:
var tempElapsed = 0
tempElapsed = tempElapsed + delta
if(tempElapsed > 0.1):
if(get_frame() == self.get_sprite_frames().get_frame_count()-1):
self.set_frame(get_frame() + 1)
tempElapsed = 0
print(str(get_frame() + 1))
The logic is pretty simple. In our process tick we increment a variable tempElapsed, until 1/10th of a second has elapsed, at which point we move on to the next frame. If we are at the last frame of our available animation, we then go back to the very first frame.
When you run it, you should see:
Pretty cool! However, instead of advancing the frame using code there is a much better approach to animation, that we will see in the next tutorial. Stay tuned.