Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

15. August 2016


Welcome back to the ongoing Defold Game Engine tutorial series, today we are going to build on the Sprites and Animation tutorial and look at three critical aspects of Defold game programming, scripting and messages.  Defold is programmed using the Lua scripting language which is beyond the scope of what we will be covering in this tutorial.  However we have already completed a Lua programming course for beginners available here.  If you are unfamiliar with Lua, it will teach you everything you need to know to get started with the language.

As with all tutorials in this series, there is an HD video version available here.


Setting up Input


If you created a default project, you will see a folder named Input, like so:


If for some reason you don’t have this input_binding file, you can create one by right clicking, selecting New->Input Binding File


The Input Binding File is a special file that maps various input devices to a text string that identifies the action to perform when that input occurs.  Double click the game.input_binding file and it will open in the editor:


You will notice there is a category for keys, mouse, gamepad, touch and text.  Right click the category you want to add an input control for and select the Add ___ trigger option.



This will create a new entry.  In the input value, drop it down and select the key/button/action you want to bind.  In the value name it.  In this example I’ve mapped KEY_SPACE to the event toggle_move.



The cool thing about this approach is you can map multiple input devices to the same action, like so:



Now the spacebar and left mouse button with both fire off the toggle_move action.  You will see how this works in just a split second.




Now that we have some input firing, lets set up a script to handle it.  Building on the project we made in the last tutorial, add a script file to your game.  In my case it looks like:



We already covered the basics of creating a script in this earlier tutorial if you need to details on how to proceed creating a script.  In the previous tutorial we created an animation called walk.  Create another one called “Idle” using the same process, but add just a single frame of animation, so it looks like this:



We are now going to add the code to toggle between the two animation states.  In your freshly created .script file, add the following code:

local currentAnimation = 0

function init(self)".","acquire_input_focus")

function on_input(self, action_id, action)
    if action_id == hash("toggle_move") and action.pressed == true then
      if self.currentAnimation == 1 then"#sprite","play_animation", {id = hash("walk")})
        self.currentAnimation = 0
      else"#sprite","play_animation", {id = hash("idle")})
        self.currentAnimation = 1
      return true -- input handled.


There are a couple key things here… first you notice the local variable currentAnimation.  This is simply going to track which animation is playing so we can switch between them.


Next we have the init() callback function.  This function is called ONCE by the Defold game engine, when the game object this script is attached to is created.  This is where you would do your various initialization and setup logic.  In this case we are telling Defold that we want to have input sent to this game object.  That way when you hit the keyboard or press a mouse for example, this scripts on_input() function will be called.  This is done by sending a message, message passing is very important and we will cover it shortly.  For now know that the first parameter in the post() call is where to send the message.  “.” is shortcode for “to the object this script is attached”.  Meanwhile ‘#’ is shorthand for “to this script itself”.  Dont worry, we will cover this in more detail in a moment.  The second parameter is the message we want to send.   In this case we are sending the message “acquire_input”, which is a predefined message type in GameObject.


Now that we’ve told Defold we respond to input, we not implement the on_input() callback function.  First we check to see what the action id is, but this value will be encoded, so simply pass it into the hash() function.  Basically we test to see if our toggle_move action that we defined earlier has been fired.  Remember, this is wired to the left mouse button or spacebar being hit.  We also check to make sure it’s a pressed event (as opposed to a release).  Next we toggle our input, if our currentAnimation value is 0 we are currently walking so now we want to change to the idle animation, and vice versa.  Notice that we change the animation once again by using a message.  In this case we are passing the message “play_animation” to the object “#sprite”.  This refers to a fragment, part of an underlying message url… dont worry, it’ll make sense in a moment.  For now just think of #sprite as saying, send this message to the sprite component of this object. 



If you look at the documentation for any given class… such as Sprite, you will see the various messages it will respond to.



Sending and receiving messages is the core of how objects in Defold communicate.  It’s a way of having different objects able to communicate and share data or respond to actions or events, while remaining loosely coupled.


Now if you run this code, it will start with the player walking.  Hitting space bar or left clicking will fire off the toggle_move event, and the animation should now switch.  Let’s look a bit closer at how you can send messages between objects.

What I did is created a new folder named other, inside of which I created a game object named other and attached a script to it, named inventively enough other.script, like so:



In your main.collection, add an instance of other, like so:



Other does absolutely nothing, but is going to illustrate how two game objects can communicate with … um… each other.  Ugh.

In other.script, add the following code:

function update(self, dt)"main:/character", "marco", { msg = "You out there?", meaningOfLife = 42 })


The update() function is the callback called by the Defold engine every single pass through your game loop.  In this case we are simple sending a message to our character game object in the main folder.  The message is called “marco” (for marco/polo).  You will notice we also pass a table with some pretty useful data in it…  msg and meaningOfLife, the first a string the second a number.  The data you fill in this table is completely optional… in fact you dont need to pass data at all.


The important part to understand is the URL we are using to post the message to.  It’s a lot like the URL you use to go to a website.  The first part (in this case) is referring to the collection the target is in, the second part is the name itself.  It doesn’t work exactly like what you might expect though, as here is the structure:


The folder name has ZERO importance in this scenario… it’s just there as a handy way for you to organize things.  The root of the url (main:/) refers entirely to the name of the collection, then the remainder of the URL, refer to values within that collection.

So we are sending this message to the character game object inside main.collection:



If we had instead wanted to send the message directly to the sprite attached to the character, we could have sent the message to main:/character#sprite


Now we can modify our code inside main to listen for this message:

function on_message(self, message_id, message, sender)
    if(message_id == hash("marco")) then


The on_message() function is called when the object your script is attached to receives a message.  In this case we check to see if the message was “marco”.  Again we encode it using the hash() function.  If you run this code you will see Polo written over and over in the console.  You will also see the data that was sent in the message, remember that table we encoded earlier.   Note the use of pprint().  This is a handy function that performs a pretty print of a table you pass in.  Basically it prints the table out in a nice easily read form.


There are a couple special message targets available as well.  @physics, @render and @system.  These actually send messages to the Defold game engine itself, the physics, rendering and system sub systems respectively.  For example, we can see that the render subsystem responds to the following messages:



So we could easily change the background color sending a message valued clear_color to @render like so:"@render:","clear_color", { color = vmath.vector4(0,0,1,1) })

In this case our data is a Vector4 with the value (0,0,1,1).  This is an RGBA color value, basically saying no red, no green, full blue and full opacity.  AKA… blue.  This will cause our background color to be blue instead of black.


This messaging system may at first seem very alien, but it quickly becomes intuitive.  You do have to keep the reference handy to see what messages each object responds to.




Finally let’s look quickly at the concept of Properties before moving on.  You’ve already dealt with several built in properties.  For example, when you created a game object, it had several built in properties already defined:



You can also easily create your own properties.  This is a great way to make code reusable, or set it to so that a coder can code, but expose some data to a designer.  The process is simple, in our script file, simply add:"MyProperty",42)

To the top of the script file.

f you are wondering just where the heck came from, it’s simply a member of Game Object which you can think of as your base class.


You can define a property anywhere, except inside the various different Defold callbacks (such as Init()).  Now you can use this property anywhere just like any other local variable, like so:



The cool part however is, now if you check in the Editor for that script, you will see the property is exposed and can easily be overriden:



The Video


blog comments powered by Disqus

Month List

Popular Comments