A LÖVE animation primer

Tutorial – LÖVE animation

Author(s):

LÖVE is an extension of the Lua language, designed to make developing games easy. In this tutorial, we'll explore this framework by creating some animated sprites.

The topic of game design can (and does) fill entire books, so we aren't going to tackle all of that today. Instead, we'll focus on a specific project, creating animated sprites in LÖVE [1], a Lua-based [2] framework that provides you with hundreds of tools and a coherent template for creating 2D games. By creating a simple animation cycle and having LÖVE show it in a window, we will explore the fundamentals of LÖVE and help you start thinking of the games you can create with the platform.

Running LÖVE

You can download LÖVE from the project's main page or use your software manager, as it is included with most mainstream distros. The current version is LÖVE 11.3.

When you run the LÖVE interpreter for the first time from the command line with love, you will initially see a screen that says "no game."

To actually see a game, you can feed the love command a directory like:

love path/to/love/project/

The directory must contain a file called main.lua, which is what the interpreter will try to run.

Anatomy of LÖVE

As the wiki [3] explains in the documentation, a LÖVE program typically consists of three parts: the load, update, and draw functions, as seen in Listing 1.

Listing 1

Basic Löve

01 function love.load ()
02   love.graphics.setBackgroundColor (0.5, 0.8, 1, 1)
03 end
04
05 function love.update ()
06 end
07
08 function love.draw ()
09 end

The love.load function (lines 1 through 3) is where you set up things. You load images, set the background, calculate the frames in each animation, set the initial values of variables, create objects, and so on. In this case, all we're doing is changing the background color of the playing field from the default black to a lighter blue to make it easier to see our animation.

The setBackgroundColor () method is a LÖVE graphics function that takes four parameters between   and 1 indicating the degree of red, green, blue, and opacity of the background. So 0, 0, 0, 0 would be completely transparent black, 0.5, 0, 0.5, 0.5 would be a semi-transparent purple, and 1, 1, 1, 1 would be a pure opaque white. As mentioned above, 0.5, 0.8, 1, 1 is an opaque light blue.

love.update (lines 5 through 6) is the main loop of the game, and where things change as the game progresses. Here you calculate the new coordinates for sprites; read in keystrokes, mouse movements, or other player-generated input; modify the playing field, and so on. When animating a character as we are doing today, this is where you would calculate which animation frame to show at each moment.

love.draw (lines 8 through 9) is where you draw what will be seen on the screen after each iteration in love.update. In today's project, that will be the actual frame of the animation we calculated.

Loaded LÖVE

For today's project, we will first load the image with the animation frames. I made a simple character called Cubey McCubeFace and gave him a simple (and probably anatomically incorrect) walk cycle for my animation (Figure 1), which is saved as cmcf.png.

Figure 1: Cubey McCubeFace's walk cycle.

As you can see, there are six frames in the animation and each frame is a 64x64 pixel square. Listing 2 shows how you would display the whole image in a LÖVE game window.

Listing 2

All Frames

01 function love.load ()
02   love.graphics.setBackgroundColor(0.5, 0.8, 1, 1)
03
04   reel = love.graphics.newImage ("images/cmcf.png")
05 end
06
07 function love.update ()
08 end
09
10 function love.draw ()
11   love.graphics.draw (reel, 100, 100)
12 end

On line 4, you use LÖVE's newimage () function to load an image from the filesystem. I'm calling the object reel, because it is like a reel of film from the olden days, containing multiple frames. On line 11, we use LÖVE's draw () function to draw the image at the 100, 100 position in the game window. Easy.

Run the program and it will show what you see in Figure 2.

Figure 2: Drawing an image in the game's window is simple.

Fortunately, grabbing cropped parts from an image and displaying them is not much harder in LÖVE thanks to something called quads.

A quad stores the coordinates of a chunk of a larger image, so it can be displayed. Listing 3 is an example of how to use a quad.

Listing 3

One Quad

01 function love.load ()
02   love.graphics.setBackgroundColor(0.5, 0.8, 1, 1)
03
04   reel = love.graphics.newImage ("images/cmcf.png")
05   frame = love.graphics.newQuad (0, 0, 64, 64, reel:getDimensions())
06 end
07
08 function love.update ()
09 end
10
11 function love.draw ()
12   love.graphics.draw (reel, frame, 100, 100)
13 end

As you can see on line 5, you make a quad by passing LÖVE's newQuad () function the coordinates of the upper left hand corner of the quad you want and then the width and height of the chunk you want to cut out. In this case, we are taking the first 64x64 square from our reel (Figure 3). The newQuad () function also needs the dimensions of the whole image as a reference.

Figure 3: Use quads to cut out chunks from larger images.

A quad is only the coordinates and dimensions of part of a drawable, that is, something that can be drawn in the draw section of your program. When you go to draw the cropped image (line 12), you need to tell the interpreter what drawable (in this case reel) the quad is referring to.

Also in Listing 3, notice the colon on line 5. A colon tells the function to use the object before the colon as the argument, much like the keyword self is used in object-oriented languages. In other words, it tells getDimensions () that it must return reel's width and height.

You could have hard-coded the image's dimensions in here like so:

frame = love.graphics.newQuad (0, 0, 64, 64, 384, 64)

But then the code would only work for images of that exact size.

Splitting Up

What you want to do is not only show one frame, but split the reel into its individual frames and store each frame (or, to be precise the quads that describe each frame) in some sort of array. This will let you pick the one you want at each moment. Fortunately, arrays, or, more specifically, tables, are a cornerstone of the Lua programming language.

Look at Listing 4 and notice how you read each frame/quad into the frames table on lines 6 to 9.

Listing 4

Separate Frames

01 function love.load ()
02   love.graphics.setBackgroundColor(0.5, 0.8, 1, 1)
03
04   reel = love.graphics.newImage ("images/cmcf.png")
05
06   frames = {}
07   for i = 0, reel:getWidth() - 64, 64 do
08     table.insert (frames, love.graphics.newQuad (i, 0, 64, 64, reel:getDimensions ()))
09   end
10 end
11
12 function love.update ()
13 end
14
15 function love.draw ()
16   love.graphics.draw (reel, frames[5], 100, 100)
17 end

On line 6 you make frames a table by assigning it an empty array. Then on line 7, you start a for loop to fill up the table. In a similar way to C/C++ and JavaScript, for loops in Lua take three arguments: the initial value for the iterator ( ), the end value for the iterator (reel:getWidth () - 64) and the increment (64) you add to the iterator after each loop.

Here's how this goes: i starts out as  , and on line 8 you use the Lua table method insert to dump the quad that goes from (0, 0) to (63, 63) into the frames table. Next time around, i's value is 64 and the quad you dump is from (64, 0) to (127, 63). This goes on until you reach the left side of the last frame at (320, 0) and you dump from there to (383, 63) into the quad table, covering all six frames.

You can now use an index to refer to any of the frames and show it in the game window, which is exactly what you do on line 16.

To run through the frames and animate your sprite, you now use the update part of your program – see Listing 5.

Listing 5

Cubey McCubeFace Walks

01 local framecounter = 1
02
03 function love.load ()
04   love.graphics.setBackgroundColor(0.5, 0.8, 1, 1)
05
06   reel = love.graphics.newImage ("images/cmcf.png")
07
08   frames = {}
09   for i = 0, reel:getWidth() - 64, 64 do
10     table.insert (frames, love.graphics.newQuad (i, 0, 64, 64, reel:getDimensions()))
11   end
12 end
13
14 function love.update ()
15   framecounter = framecounter + 1
16   if framecounter > 6 then
17     framecounter =  1
18   end
19 end
20
21 function love.draw ()
22   love.graphics.draw (reel, frames[framecounter], 100, 100)
23 end

The new thing here is that we have a variable, framecounter, that does what it says on the tin: It starts out as 1 (line 1) and increments to 6 on each iteration of update () (lines 15 to 18). You can then use it to show each of the frames in the draw () section (line 22).

Run the program and Cubey McCubeFace walks … but badly.

LÖVE in Time

When you run Listing 5, Cubey "walks," but the movement is jittery and way too fast to appreciate as a smooth animation.

That is because you are using the speed of your processors to run the animation. Depending on the load of your CPU, the execution of your program will be faster or slower and, in consequence, so will your animation. The speed of your animation will also vary depending on the speed of the device you use. This is not good. You cannot have your game run so fast that it's unplayable or so slow that it's sluggish and boring.

What you need is to run the animation in game time. Game time means that, if you want an action to take half a second to complete, it will take half a second regardless of the load of the processors or the power of the machine it is running on.

Game time is implemented in LÖVE via the dt variable. The idea behind dt is simple: It contains the time that has passed since the last time update was called. Just with that information you can make actions last exactly as long as intended.

Say you want a full walk cycle of Cubey McCubeFace to last exactly half a second. You could modify your program to look like Listing 6.

Listing 6

Cubey McCubeFace Walks Slow

01 local framecounter = 1
02 local time = 0
03
04 function love.load ()
05   love.graphics.setBackgroundColor(0.5, 0.8, 1, 1)
06
07   reel = love.graphics.newImage ("images/cmcf.png")
08
09   frames = {}
10   for i = 0, reel:getWidth() - 64, 64 do
11     table.insert (frames, love.graphics.newQuad (i, 0, 64, 64, reel:getDimensions()))
12   end
13 end
14
15 function love.update (dt)
16   time = time + dt
17   if time >= 0.5 then
18     time = 0
19   end
20
21   framecounter = math.floor ((time/0.5) * #frames) + 1
22 end
23
24 function love.draw ()
25   love.graphics.draw (reel, frames[framecounter], 100, 100)
26 end

You set a new variable time to   (line 2), and each time you enter update () you add dt to time (notice you need to make dt a parameter of love.update () for this to work). Then, if you divide time by the duration you want for your animation (0.5 seconds, in this case) as shown on line 21, you will have the stage in the animation counting from when time was  . For example, if time is 0.25, a quarter of a second has passed since the animation started:

0.25 / 0.5 = 0.5

This tells your program you are halfway through the animation.

Now multiply that by the number of frames (#frames – you use # to get the number of items in any table), and you will get a number between zero and five. Get rid of the decimals using Lua's math.floor () function, add one and you've got a number between one and six, the number of the frame you need to show.

As soon as the time reaches the duration of the animation, you reset time to   (line 17 through 19) and start all over again.

Run the program, and you will see that Cubey McCubeFace runs through one walk cycle every half a second.

Clean LÖVE

To keep things nice and tidy, you can take all the initiation and calculations out to separate functions. To make your main.lua file even cleaner, you can then separate those functions into a different file.

In this example, Listing 7 is your main file, and Listing 8 is where all the gory stuff goes.

Listing 8

animation.lua

01 function animation (reel, framesize, duration, pos)
02   local animation = {}
03
04   animation.reel = love.graphics.newImage (reel)
05
06   animation.frames = {}
07   for i = 0, animation.reel:getWidth() - framesize[1], framesize [1] do
08     table.insert (animation.frames, love.graphics.newQuad (i, 0, framesize[1], framesize[2], animation.reel:getDimensions()))
09   end
10
11   animation.duration = duration
12   animation.frame = 1
13   animation.time = 0
14
15   animation.pos = pos
16
17   return animation
18 end
19
20  function framecounter (time, duration)
21   if time >= duration then
22     time = 0
23   end
24   return math.floor ((time / cmcf.walk.duration) * #cmcf.walk.frames) + 1, time
25 end

Listing 7

main.lua

01 require 'animation'
02 local time = 0
03
04 function love.load ()
05   love.graphics.setBackgroundColor(0.5, 0.8, 1, 1)
06
07   cmcf = {}
08   cmcf.walk = animation ("images/cmcf.png", {64, 64}, 0.5, {100, 100})
09 end
10
11 function love.update (dt)
12   cmcf.walk.frame, cmcf.walk.time = framecounter (cmcf.walk.time + dt, cmcf.walk.duration)
13 end
14
15 function love.draw ()
16   love.graphics.draw (cmcf.walk.reel, cmcf.walk.frames[cmcf.walk.frame], unpack (cmcf.walk.pos))
17 end

To include the contents of Listing 8 in your main.lua file, all you need is the require command (line 1).

Most of what is going on in Listing 8 should be self-explanatory, but it is worth pointing out how Lua tables can act like pseudo-classes that will allow you to create a cmcf (Cubey McCubeFace) walk cycle type-object, a jump cycle type-object, a run cycle type-object, and so on.

User Libraries

That is how you can create an animation from scratch using LÖVE's built-in tools. But you could also use anim8 [4], a LÖVE library that takes the drudgery out of animating sprites and lets you have the different frames on a grid (as opposed to just on a line) and pick what frames to use in an animation.

Like anim8, there are many other libraries for LÖVE, that apart from making animation easy, cover physics, isometric 3D tiles, collision detection, and much more. Before putting yourself through the hassle of programming a whole super-framework from scratch, check that someone hasn't already done it for you [5] – unless you are doing so to learn the basics. (Also, for a brief word about the editor you use for programming, see the box "Ideal IDE.")

Ideal IDE

Although your regular, favorite text editor will do just fine, there is some merit in going with ZeroBrane Studio [6] (Figure 4). Not only is it an efficient little editor with all the bells and whistles you need for Lua programming (syntax highlighting, text completion, file management, etc.), it also comes with hooks to a bunch of the most popular Lua interpreters, including LÖVE and Moai, another framework for gaming development.

Go to Project | Lua Interpreter in the menu, pick LÖVE from the list, and you'll be able to run and debug your game directly from the IDE.

Figure 4: ZeroBrane Studio is probably the best IDE for programming in Lua.

LÖVE Platforms

Your LÖVE games can be ported to other platforms, including Windows, iOS, and Android (Figure 5), and the LÖVE wiki explains in detail how to do that [7]. However, you can test-run your program on Android before you go to all the trouble of compiling or pushing it through a toolchain to get a native APK.

Figure 5: Cubey McCubeFace goes walking on an Android phone.

On your computer, you have to create a file called conf.lua, like the one in Listing 9.

Listing 9

conf.lua

01 function love.conf(t)
02     t.version = "XX.X"
03 end

"XX.X" is the version of the LÖVE interpreter on your computer. You can find this out by running the LÖVE interpreter from the command line with love. The version of LÖVE is shown in the titlebar.

Put conf.lua in the same directory as your main.lua file, enter the directory and zip everything up with

zip -9 -r YourGame.love .

You can choose a different name from YourGame, of course, but your zipped file must have the extension .love.

On your phone, download the LÖVE interpreter for Android from Google Play [8] and then copy the .love file from your computer over to your Android device. You'll be able to run it with your newly installed LÖVE interpreter.

Conclusions

We have only touched on one of the many superficial tasks you will have to carry out when creating your own game. However, my hope is to tempt you to get your toes wet and to help you get your head round the most basic principles of programming with LÖVE. As a fan of old-school, casual gaming, I can't wait to see what you do with it.

Infos

  1. LÖVE game framework: https://love2d.org
  2. Lua programming language: https://www.lua.org/
  3. LÖVE wiki: https://love2d.org/wiki/Tutorial:Callback_Functions
  4. The anim8 library for LÖVE: https://love2d.org/forums/viewtopic.php?f=5&t=8281
  5. List of LÖVE libraries: https://www.love2d.org/wiki/Category:Libraries
  6. ZeroBrane Studio: https://studio.zerobrane.com/
  7. How to port your games to other platforms: https://love2d.org/wiki/Game_Distribution
  8. LÖVE interpreter for Android: https://play.google.com/store/apps/details?id=org.love2d.android