Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon
23. February 2015


Until this point in the series we have only created single scene games.  In any non trivial application you are often going to want to have several scenes make up your game.  For example you might have a scene for your title screen/intro, then a main menu, then a game playing then finally a game over scene.  Today we are going to look at how to do exactly this.  We are also going to look at sharing information between those scenes.


This scene is available as an HD video here.


Creating Multiple Scenes


First and foremost, you always need to have at least one scene to start up.  Let’s go ahead and create one, the Title screen seems logical enough.  Create a scene that draws a simple graphic, called it “title_scene.scn” and set it as your startup scene.  If you are unfamiliar with this step, please see prior tutorial parts.  Once complete it should look something like this:



Next we want to create a scene to transition to.  I called mine game.scn.  It may not be completely obvious, but you actually close your scene to create the new scene.  Select Scene->New Scene:


Then say yes to the scary dialog that pops up ( of course, we assume you’ve saved your scene and set it as the startup scene already! ):



Now in the second scene, I just created a simple Panel, with a pair of label controls, like so:



It doesn’t really matter what you do.  The labels are just to show that information can be shared between Scenes.  Our game isn’t actually going to do anything.



Ok… so now we have our two scenes… how are we going to wire them all together?  Well that requires a script.  Re-open the title_scene.scn scene.  There is a handy Open Prev Scene menu option, or you can use open Scene…



Adding a Script to control scene switching


Now that we have our original scene selected, we need to add a script to it.  To do this, switch to the Resources tab and select the New Resource icon:



For type select GDScript:



I named mine ‘’.


Now we write out our script.  We are going to be auto loading this as a node into our game when our application starts, so we need to inherit from Node or a Node derived class.  In my case I used node.  You can inherit a class using the extends keyword.


Here is the code for our simple Node script.  We create a function so scenes can switch between scenes, and demonstrate getting a session variable, as well as setting a global variable.

extends Node

#The currently active scene
var currentScene = null

#just some data for our game.  It could be HPs, Alignment, Direction, etc...
var PlayerName = "Mike"

func _ready():
   #On load set the current scene to the last scene available
   currentScene = get_tree().get_root().get_child(get_tree().get_root().get_child_count() -1)
   #Demonstrate setting a global variable.
# create a function to switch between scenes 
func setScene(scene):
   #clean up the current scene
   #load the file passed in as the param "scene"
   var s = ResourceLoader.load(scene)
   #create an instance of our scene
   currentScene = s.instance()
   # add scene to root
#simple accessor function to retrieve playerName   
func getPlayerName():
   return PlayerName


Autoload script on startup


Be sure to save your newly created script.  Now we want to set it so that this screen runs automatically when our game is started.

To do this, go to Scene->Project Settings.

In the resulting dialog, you want to select the AutoLoad tab.  Now you specify the script you want to autoload, and the name you want the node to be known as.  This is case sensitive by the way.

In path, select your newly created  In Node Name call it globals then click Add:



Now this script will be run automatically when your game or application starts up!


Now that we can switch scenes, let’s make us of this ability.  In your title_scene.scn project, attach a script to the image you used.  Personally I used a TextureFrame to hold my title screen.    We are simply going to check for the user pressing the left mouse button, and if they do, we are going to switch scenes.

extends TextureFrame

func _ready():
func _process(delta):


As you can see you can access the script by getting it as a node using the name you provided in the AutoLoad dialog.  Once again this value is case sensitive and you have to include the /root/ part. 


So, once we click our title image, it should load our other scene.  Let’s add a bit of logic to it.  Load the game.scn ( yes, I wish their was a project mode that prevented this switching between scenes stuff… ), attach a script and add the following code:

extends Panel

func _ready():
   var name = get_node("/root/globals").getPlayerName()
   get_node("Label").set_text(str(name, " is the greatest player ever!"))

   var powerLevel = Globals.get("MAX_POWER_LEVEL")
   get_node("Label2").set_text(str("Maximum power level is ", powerLevel))


This code illustrates too simple concepts... calling a global instance ( Singleton in Godot parlance btw ), such as setScene() or getPlayerName() or calling a global variable. Both methods make it very easy to share data between various scenes, escentially forming the backbone of your application.


The Video



20. February 2015


This tutorial is available as an HD video here.


In this tutorial we are going to look at the UI aspects of the Godot game engine.  If you have prior experience with other game engines, you will probably be shocked by the number of UI widgets and containers that ship with Godot.  While many of these controls would never be used in a game, they are absolutely invaluable for creating tools.  Of course they are also great for making games, making implementing your UI a breeze.


Using Controls in Godot is just like using any other Node, although the relationship between them is where things vary the most.  Let’s take a quick look at what’s included:



All controls inherit from Control, which in turn inherits from CanvasItem, which allows it to be drawn on screen.  At the end of the day there are three categories of Controls: UI Wdigets, Containers and Popup Windows.  The containers are controls that contain other controls.  Quite often they will automatically arrange their contents for you.  Popup Windows are exactly that, dialog boxes you can display for things like messages, file selection, etc.  Then there is everything else…  these are the various widgets you can use in your application, things like Buttons, Labels and even video players.


Your First GUI Application


Let’s jump right in, show how controls work and the relationship between containers and controls.  We are going to create a simple menu where our controls are automatically laid out vertically.


Start out by creating a VBoxContainer, which is a box of controls that automatically arranges it’s children vertically.

Create a VBoxContainer Node:



Size it somewhat centered on your screen, like so:



Now in the Scene tab, make sure VBoxController is selected and create a new node:



Select MenuButton:



Repeat a couple times so you have multiple buttons.  Your scene hierarchy should look like this:



Next select MenuButton and in the Inspector set the Text:



You can set a number of properties that control the button’s appearance.  Keep in mind, like all other nodes in Godot, the Control inherits positional information from it’s parent container.


As you add text to your controls, you can see that the container automatically aligns them vertically within:



Now, what if you want to expand the labels to use the entire space available within the parent control?  That can easily be accomplished too.  For each button, go into the Inspector and drop down the Vertical setting and make sure Expand is selected:


Now you should see the menu laid out like this:



You may find the Font to be laughably small… so lets quickly create a new font.  We covered this in the past but a quick recap.  Select Import->Font:



Select a ttf file and save it as a fnt file, like so:



Now you can the font of each menu item using the Load option of Custom Font in the Inspector with a Button selected, like so:



After setting the font, sizes should change automatically, like so:



You need to perform this task for each Button… or…


Using a Theme


Godot has limited theming support, but in reality that mostly just means you can set a common font.  Select the VBoxContainer, locate Theme and create a new one:



Now drop it down again and select Edit:


This will now bring you to the theme editor window, which contains a preview of how your theme looks with various controls:



In the Inspector, select Theme->Default Font and load our font:



When happy with your theme, select Save Resource button:



Save it as a .thm file:



Now all of the controls in your container should be updated ( You may have to load the theme again using Theme->Load ):



Connecting Code to your Control


Now that we have our controls wired up, lets go ahead and wire them up to do something. 


First lets attach a script to our container.  In the Scene tab, select the VBoxController and click the new script button:



Create it using whatever settings you wish, like so:



Now select your first MenuButton and click the Connections button:



Select Pressed, then press the Connect button:



Make sure the container is selected, then press Connect:



This will create a method named _on_MenuButton_pressed in the VBoxContainer script.


Now edit your code like so:



Now run your game and you should see:



And if you click the first button you should see:



There are several more controls available, but the basic process of using them is nearly identical so I wont go into it.  For more details on laying out controls or more examples ( such as using pop-ups and Bitmap buttons ), be sure to watch the video tutorial as well!


The Video Version



6. February 2015


This tutorial is available as an HD video here.

Today we are going to look at using audio with Godot.  If you’ve used other game engines you will find the process is probably quite a bit different and perhaps a little unintuitive but in the end rather simple and quite power.  It is a bit of a multistep process so let’s jump right in.


For this example you are going to need a couple audio files.  Personally I get most of the audio files for my tutorials from a site called  Now a moment about audio formats.


The Two Kinds of Audio


There are two audio types in Godot ( and many other game engines ).  Samples and Streams.  A sample is an uncompressed piece of sound that is loaded into memory.  Samples take up more memory but a great deal less processing power.  In Godot you create samples by importing them as WAV files.  Streams on the other hand are instead compressed audio files (think MP3), often much longer in duration.  These you simply copy into your project, Godot supports MPC and Ogg Vorbis formats. 


Generally samples are used for in game quick sound effects, while streams are used for background music.  There is a pretty good chance your audio isn’t in WAV, Ogg or MPC format.  If it isn’t, I highly recommend the free program Audacity for converting between formats.


Playing an Audio Sample


As I said earlier, samples are uncompressed audio files generally used for sound effects and it’s a multistep process loading and playing one.  Its also quite common to play multiple of the sample sample at once.  Ok, let’s look at that process.


First you need to create a SamplePlayer.  This is a node you can add to your scene.  There are 3 kinds of players, SamplePlayer, SamplePlayer2D and SpatialSamplePlayer.  They all accomplish the same thing, however 2D has additional stereo support and can be positioned in your 2D world, while Spatial enables you to position your audio source in 3D to simulate positional audio.  In this tutorial we are just going to use the simple SamplePlayer.  We may cover the other two in later tutorials.


Creating the SamplePlayer Node

Add a new SamplePlayer node to your scene:




Creating a new SampleLibrary


Now we need to create a Sample library.  With your SamplePlayer selected in the Scene panel, in Inspector locate Samples, drop in down and select New SampleLibrary:



Now drop it down again and select Edit:



This will change your active view to the samples library view.  Note, the tabs above ( 2d, 3d, etc ) will not navigate you out of this screen currently.  To get back to your 2D scene view, select a different node in the Scene panel to the right.



Importing an Audio Sample


We can now use this window to add our samples to the library… guess we need a sample.  For that you use the Import menu.  Select Import->Audio Sample:



This will bring up an Import Audio Samples dialog like so:


Under source, navigate to the WAV file you want to import.  For target path select the location within your project you want it to reside.  Under options you have several configuration settings, such as changing the amount of data used/fidelity of your sound ( Max Rate Hz ), making it Mono vs Stereo or forcing it to be 8bit, which is a really low fidelity, single channel but tiny audio file.  For now just use the default settings.  When you click Import a new “smp” file will be added to your project:



Adding Sample to Audio Library


Now that we have our sample, we need to add it to our library.  You can use the same sample in multiple libraries.  In the Edit Sample window select the open icon:



Select your newly imported sample.  It should now appear in the list like so:


Here you can preview the sample, change it’s default volume using dB (decibel) or change it’s pitch using the PScale value.  You can add multiple samples to the sample library.  The yellow blob you see in the middle of the screen is the waveform of the audio… there are two of them because this is a stereo example.  As you can see by the fact they are identical waveforms, this is actually really wasteful, so you would be best to save the file size and import this as a mono sample instead!


Playing an Audio Sample using SamplePlayer


Now that we have an SampleLibrary with a sample in it, we can now go ahead and play it.  Let’s add a script to our SamplePlayer node that will automatically play the sound when we begin.  It’s incredibly simple, like so:

extends SamplePlayer

func _ready():

Yeah... that's it.  You simply call the play method of SamplePlayer and pass in the name as defined in the Sample Library.


Of course, rarely are you going to have a SamplePlayer play it’s own sounds.  What is much more likely is you would add a SamplePlayer to the base of your scene tree, then call it from child nodes within the scene.  Don’t worry, that is equally simple… let’s do it!


Add a Button Node to your scene, attach a script to it, then hit the Connections icon and create a default handler for the “pressed()” connection.




Generally you wouldn’t use the SamplePlayer as the root scene node, but that’s what I’ve got so I went with it…  Now in your button handler, you can get a reference to the SamplePlayer using:


extends Button

func _ready():

func _on_Button_pressed():


One important thing to be aware of…  the value passed into play() is case sensitive!  So if I passed in “Siren” it wouldn’t play anything!  So basically playing a sample is simply a matter of getting a reference to the SamplePlayer node and calling the play method.


So… that’s how you play a single sound… how do you play multiple at once… well, that’s a matter of voices.  A Voice can be thought of as a playing instance of a single sound.  If you want multiple sounds to play at once, you need multiple voices in your SamplePlayer.  You can set that value in the Inspector of the player, like so:



Now when you run the application, each time you click the button a new version of your sound effect will start playing concurrent to the previous version.  What if you only want a single instance of a sound effect to play at a time?  Well that can be done too…  when you call play() there is an optional second parameter that tells Godot wether the sound is unqiue or not.  Set it to true, like so:



And each time your press the button the sound effect will instead start over.


One final critical thing to understand is how to manipulate ( stop, pause, change volume, etc… ) a single instance of a sound playing.  This is done using Voice IDs, once of which is returned when you play a sample.  So the following example plays a sound and immediately sets it’s volume to 50%:


func _on_Button_pressed():
   var player = get_tree().get_root().get_node("SamplePlayer")
   var voiceID ="siren")
   player.set_volume(voiceID, 0.5)


So you used the voice ID to interact with already running samples.  These only last as along as the sample is playing.


Playing Music


Now let’s look at streaming a file instead.  The process is very similar, but instead you add a StreamPlayer node:



Now copy an MPC or OGG file into your project file folder using Windows Explorer or Mac Finder.  Now in Inspector with StreamPlayer selected, locate the Stream property and select the appropriate type, I’m using AudioStreamOGGVorbis:


Now drop it down again and select Load:



Select the file you copied into your project.  Attach a script to a Node in your Scene… for demo reasons I’m just adding it to the StreamPlayer itself.  Then you can use the code:

extends StreamPlayer

func _ready():


You don’t actually need code to accomplish this.  If you want the StreamPlayer to play it’s song automatically, you can simply set the Autoplay property:



Now one really common thing to do in games is to play a different song after the current song finished playing… let’s take a look at how you can accomplish this:


extends StreamPlayer

var song1
var song2
var currentSong = song1

func _ready():
   song2 = load("song2.ogg")
func _process(delta):
   if(self.is_playing() != true):
      if(self.get_stream() == song1):



The Video Version



28. January 2015


This tutorial is available in video form here or embedded below. 


Now might be a good time to pause and look at the life cycle of a typical program, as this can be a bit confusing with Godot yet is something you really need to understand.  Every non-trivial game has a game loop somewhere.  This is the code that runs after a program starts and is basically the heart of your application.  In pseudo code, it might look something like this:


main() {
   scene = createScene()


At it's heart it’s a glorified loop that runs over and over, checking for input, updating the scene and rendering the results until told to stop.


Godot of course is no exception, although by default this behavior is hidden from you as is the norm with game engines.  Instead the object that owns your scene is a SceneTree which itself inherits the MainLoop, which provides the above functionality.  A default one is provided for you, but if you wish you can implement your own, more on that below. 


What you should however realize is that this SceneTree is the beating heart of your application.  Every frame it calls it’s active scene passing in all the input that has occurred, as well as updating nodes that request updating.  We will look at this process now.  One important thing to be aware of… Nodes can access the SceneTree using the method .get_tree().


Updating a Node every frame


Ok, so that’s the basics of how program execution flows, now let’s take a look at a more practical example.  Let’s say for example we have a Sprite that we want to update every frame.  How do we tell our MainLoop that we want or Node to be updated?  Fortunately it’s quite simple. 


Create a Sprite node, add a graphic, position it on the screen then add a new script to it.  All of this was covered in the previous tutorial if you are unsure how to proceed.


Now that we have a Script attached, first we need to tell it we want to receive updates.  That is, every iteration of the main loop, we want our script to be called.  This is a two part process, pun not intended… much.  First, in your _ready function, you tell Godot you want to receive updates by called set_process(true).  Then you override the virtual function _process().


Let’s take a look at a simple sprite that moves right until it hits the edge of the screen, at which point it wraps around.

extends Sprite

func _ready():
func _process(delta):
   var cur_pos = self.get_pos()
   cur_pos.x += 100 * delta
   # wrap around screen
   if(cur_pos.x > self.get_viewport_rect().size.width + self.get_item_rect().size.width/2):
      cur_pos.x = -self.get_item_rect().size.width/2

set_process tells Godot to call this nodes _process() function.  The value passed in, delta, is the elapsed amount of time since the last time _process was called.  As you can see in the above example, this value can be used to animate at a constant rate.  The above example will update the X value by 100 pixels per second.  Your end result should look something like this:




So, in a nutshell, if your want to handle updates in your Node derived object, you simply call set_process(true) and provide a _process(float) override.


Handling Input by Polling


That moves us on to handling input.  You will notice that Input and Process handling are very similar.  There are a couple ways you can handle input in Godot.  Let’s start with the easiest, polling.


You can poll input at any time using the global object Input, like so:

func _process(delta):


This checks  first if the ESCAPE key, then if the SHIFT key (is also!) pressed.  If so we tell the SceneTree to exit the application.  As I said earlier, a node can access it’s SceneTree using get_tree().


In addition to polling for keyboard, there are also methods is_joy_button_pressed(), is_mouse_button_pressed() and is_action_pressed() which will make more sense in the near future.  You can also poll for status.  For example, to check the mouse cursor or touch location you could:


func _process(delta):
      print(str("Mouse at location:",Input.get_mouse_pos(), " moving at speed: ", Input.get_mouse_speed()));

There are other inputs you can poll as well, mostly mobile based, but they all use a very similar interface. I will cover mobile specific controls at a later point in this series.


Handling Input as Event Driven


You can also have Godot hand your application all the Input events as they occur and choose what to process.  Just like handling updates, you have to register to receive input events, like so:

func _ready():


Then you override the function _input, which takes an InputEvent as a parameter.

func _input(event):
   # if user left clicks
   if(event.type == InputEvent.MOUSE_BUTTON):
      if(event.button_index == 1):
   # on keyboard cursor key
   if(event.type == InputEvent.KEY):
      var curPos = self.get_pos()
      if(event.scancode == KEY_RIGHT):
         curPos.x+= 10

      if(event.scancode == KEY_LEFT):
         curPos.x-= 10


The above example handles a couple different scenarios.  First if the user clicks the left button, we set the position to the mouse’s current x and y location, as passed in by the InputEvent class.  Notice in this case I tested for button by index instead of the define BUTTON_LEFT like earlier.  There should be no functional difference, although this would allow you to test for buttons for which a mapping isn’t defined, such as one of those insane 12 button mouse.  Next we check to see if the event is a KEY event and if it is we check which key.  In the event of the right or left arrow, we update our position accordingly.


Sometimes however when you handle an event you want it done and gone.  By default all events will continue to be broadcast to all event receivers.  When you don’t want this behavior, it’s fairly simple to tell Godot that an event is handled.  From the above example, let’s swallow the event in the case of it being an InputEvent.KEY.  This means only this class will have access to keyboard events ( well… and GUI controls, which actually get their crack at the events earlier on ).

   # on keyboard cursor key
   if(event.type == InputEvent.KEY):
      var curPos = self.get_pos()


Calling set_input_handled() will cause the InputEvent to propagate no further.


Finally it’s possible you want to do a catch all.  Perhaps you want to log all of the unhandled input events that occurred.  This can also be done and you also have to register for this behavior, like so:

func _ready():

Then you simply override the corresponding function:

func _unhandled_input(event):
   print(str("An event was unhandled ",event))

In this case we simply log the event out to the console.  Warning though, there will be A LOT of them.  Just no keyboard events, since we are now eating those!


Input Maps


Quite often you want several commands to perform the same action.  For example you want pushing right on the controller d-pad to perform the same action as pushing the right arrow key.  Or perhaps you want to let the user define their own controls?  In both of these cases and input alias system is incredibly useful… and thankfully Godot has one built in… InputMaps.


You may have noticed the InputMap tab when we were in Project Settings earlier… if not open up Project Settings now…



Here you can see a number of mappings have already been defined for UI actions.  Lets go ahead and create a map of our own, MOVE_RIGHT.

At the top in Action enter MOVE_RIGHT


Then click Add


A new entry will be added to the bottom of the page, like so:


Click the + icon and add a new mapping of type Key



You will then be prompted to press a key:



Repeat this process and instead select another device… im going to also map the right mouse button, like so:



Your Input Map should now look something like this:



Now click the Save button and close the dialog. 

Now in code you can easily check activity using the input map, like so:

func _process(delta):
      var cur_pos = self.get_pos()
      cur_pos.x += 1

This code will run if either condition is true… the Right key is pressed or the Right mouse button is.  The above example is polled, but it’s just as easy to use an InputMap with event driven code, like so:

func _input(event):


One warning here however…  Actions are more states ( as in On or Off ) than they are Events, so it probably makes a great deal more sense dealing with them the former ( polling ) than the later ( event driven ).


A Peek Behind the Curtain


If you are like me, you probably aren’t content with not knowing exactly what is going on behind the scenes.  Black boxes just aren’t my thing and this is one of the great things about Godot being open-source, there are no black boxes!  So if you want to understand exactly how program flow works, it helps to jump into the source code.



I figured I would bold that.  The following information is just for people that want to understand a bit more what is happening behind the scenes…  We are going to hunt down the actual main loop in the source code, and essentially it’s right here in the function main/main.cpp.  Specifically the method iteration() is effectively the main loop:

bool Main::iteration() {

   uint64_t ticks=OS::get_singleton()->get_ticks_usec();
   uint64_t ticks_elapsed=ticks-last_ticks;


   double step=(double)ticks_elapsed / 1000000.0;

   float frame_slice=1.0/OS::get_singleton()->get_iterations_per_second();

   if (step>frame_slice*8)


   float time_scale = OS::get_singleton()->get_time_scale();

   bool exit=false;

   int iters = 0;

   while(time_accum>frame_slice) {

      uint64_t fixed_begin = OS::get_singleton()->get_ticks_usec();



      if (OS::get_singleton()->get_main_loop()->iteration( frame_slice*time_scale )) {



      //if (AudioServer::get_singleton())
      // AudioServer::get_singleton()->update();


   uint64_t idle_begin = OS::get_singleton()->get_ticks_usec();

   OS::get_singleton()->get_main_loop()->idle( step*time_scale );

   if (SpatialSoundServer::get_singleton())
      SpatialSoundServer::get_singleton()->update( step*time_scale );
   if (SpatialSound2DServer::get_singleton())
      SpatialSound2DServer::get_singleton()->update( step*time_scale );

   if (OS::get_singleton()->can_draw()) {

      if ((!force_redraw_requested) && OS::get_singleton()->is_in_low_processor_usage_mode()) {
         if (VisualServer::get_singleton()->has_changed()) {
            VisualServer::get_singleton()->draw(); // flush visual commands
      } else {
         VisualServer::get_singleton()->draw(); // flush visual commands
         force_redraw_requested = false;
   } else {
      VisualServer::get_singleton()->flush(); // flush visual commands

   if (AudioServer::get_singleton())

   for(int i=0;i<ScriptServer::get_language_count();i++) {


   if (script_debugger)

   // x11_delay_usec(10000);

   if (frame>1000000) {

      if (GLOBAL_DEF("debug/print_fps", OS::get_singleton()->is_stdout_verbose())) {
         print_line("FPS: "+itos(frames));


      if (GLOBAL_DEF("debug/print_metrics", false)) {



   if (OS::get_singleton()->is_in_low_processor_usage_mode() || !OS::get_singleton()->can_draw())
      OS::get_singleton()->delay_usec(25000); //apply some delay to force idle time
   else {
      uint32_t frame_delay = OS::get_singleton()->get_frame_delay();
      if (frame_delay)
         OS::get_singleton()->delay_usec( OS::get_singleton()->get_frame_delay()*1000 );

   int taret_fps = OS::get_singleton()->get_target_fps();
   if (taret_fps>0) {
      uint64_t time_step = 1000000L/taret_fps;
      target_ticks += time_step;
      uint64_t current_ticks = OS::get_singleton()->get_ticks_usec();
      if (current_ticks<target_ticks) OS::get_singleton()->delay_usec(target_ticks-current_ticks);
      current_ticks = OS::get_singleton()->get_ticks_usec();
      target_ticks = MIN(MAX(target_ticks,current_ticks-time_step),current_ticks+time_step);

   return exit;


If you take a good look at that code, you'll notice beyond the complexity it's actually remarkably close to the pseudo code I started this post with. As I said, most game loops start looking pretty same-y over time. Now looking at the code you will notice a number of calls like this:


OS::get_singleton()->get_main_loop()->iteration( frame_slice*time_scale ))

These are callbacks in to the MainLoop we mentioned earlier. By default Godot implements one in C++ you can access here in core/os/main_loop.cpp:


#include "main_loop.h"
#include "script_language.h"

void MainLoop::_bind_methods() {




void MainLoop::set_init_script(const Ref<Script>& p_init_script) {


MainLoop::MainLoop() {


void MainLoop::input_text( const String& p_text ) {


void MainLoop::input_event( const InputEvent& p_event ) {

   if (get_script_instance())


void MainLoop::init() {

   if (init_script.is_valid())

   if (get_script_instance())

bool MainLoop::iteration(float p_time) {

   if (get_script_instance())
      return get_script_instance()->call("iteration",p_time);

   return false;

bool MainLoop::idle(float p_time) {

   if (get_script_instance())
      return get_script_instance()->call("idle",p_time);

   return false;
void MainLoop::finish() {

   if (get_script_instance()) {
      set_script(RefPtr()); //clear script



The default main loop in turn is mostly a set of callbacks into the active script.  You can easily replace this MainLoop implementation with your own, either in GDScript or C++.    Simply pass your class name in the to main_loop_type value in Project Settings:



Granted, very few people are actually going to need to do this…  mostly the people that want to live entirely in C++ land.  I do however think it’s extremely valuable to understand what is going on behind the scenes in a game engine!


The Video



26. January 2015


In this tutorial we are going to be taking a look at what seems to be everyone’s favorite subject, graphics.  We are going to start by creating a Sprite.  A Sprite is basically a 2D image with spatial information such as scale, rotation and position.  We are then going to take a closer look at coordinates and viewports, critical concepts to understand.


The video version of this tutorial is available here.


Creating a Sprite


Start by creating a new node in your scene panel.



Locate and create a “Sprite” node in the resulting dialog:



Now you need an image file to use as a Sprite.  You could simply copy one into the folder structure of your project at the file system level but in this case I am going to use the Import menu.  Select Import->2D Texture:



Locate the file ( it doesn’t have to be in your project directory ), and pick where you want it to be located locally, like so:



Once again, you do not have to import this way, you could have simply copied in the files to your project directory!


Ok, now that we have an image, let’s use it with our Sprite.  With the Sprite selected, in the Inspector panel locate Texture, drop it down and select Load.


Select your newly imported 2D Texture.


Now in your 2D view you will see your sprite positioned centered about the screen origin:



Navigating the 2D View


Now might be a good time to do a quick overview of how the 2D view works.  Let’s start off by looking at the 2D view itself

(Click image to expand)



This is where you position and manipulate the nodes that make up your world.  As you can see, the X-axis is marked in red and the Y axis is marked in green.  Where the two join, that is the world origin.  In this particular example, the viewport ( blue rectangle ) is in the negative Y and positive X quadrant.  However, child nodes positioning is relative to it’s parent, so to our sprite 0,0 appears to be the top left corner of the screen.


The selected object is surrounded by a manipulator cage.  This can be used to easily scale the image, while left clicking and dragging within the cage will move the selected node around.  Remember you can also set positioning information in the Inspector numerically.  You can switch to Rotate mode to rotate an object, objects rotate relative to their center point.  Pan on the other hand allows you to move the camera itself around, enabling you to “pan” through your world.


Mouse Controls:

Button Action
Left Mouse Button Click Select clicked node
Left Mouse Button Click + Drag Translate or Rotate selected
Middle Mouse Button Pan the scene
Scroll Wheel Zoom in/out


Keyboard Controls

Key Action
Q Select Mode
W Translate/Move Mode
E Rotate Mode
Arrow Keys Move selected, very fine
Shift + Arrow Keys Move selected
ESC Unselect
F1 Help Panel
F Center Camera on Selected
Ctrl + F Frame Camera (Zoom to fit) on Selected
Ctrl + P Expand to selected node’s parent
V (hold) Move pivot point




Some times snapping can be incredibly useful when laying out a scene.  Snapping essentially super imposes a grid over your scene and “snaps” the selected to that grid.  To enable Snapping, simply select Use Snap from the Edit Menu.



Using Configure Snap you can set the size of each grid in the snapping overlay.   Now your scene will look like this:



Note, this grid is just there to help you with accurate placement only!  It will not appear when you render your game.  Turn if off again by clicking Use Snap again.  If you are working on a tile based game, snapping can be invaluable.


Rotating, Translating and Scaling a Sprite using Code


So that covers how to add a Sprite to your world and how to navigate the 2D view, let’s take a quick look at the three most commonly performed actions… translating(moving), scaling and rotating.  The following code does all three:

extends Sprite

func _ready():

      #translate to center of the parent, in this case, the viewport
   var newPos = Vector2(self.get_parent().get_rect().size.width/2,self.get_parent().get_rect().size.height/2)
   #rotate by 90 degrees.  set_rot takes radians so we need to convert using in-built function
   #scale by 2x
func _draw():  
   # each frame draw a bounding rect to show boundaries clearer

And when you run that, you should see:



Please note, I quite often use self because I find it adds a bit of clarity and frankly makes code completion easier.  In the above code, “self” is the inherited class “Sprite”.  If you prefer shorter code, you can omit the use of self and it is functionally identical!


One important thing to understand is, all of these transformations happened relative to the Sprite’s pivot point, which by default is at it’s center.  If you zoom in on your Sprite object you should be able to see the pivot point:



It’s the T like cross hair.  This point determines where local transforms occur relative to.  For example, when you say “rotate 90 degrees’ you are rotating 90 degrees around this point.  In the 2D editor, you can move this point ( or more accurately, move the Sprite relative to this point ), by holding the V key down while moving.


Here for example I hit W then left click dragged to move the sprite slightly.  Then I held down V and moved the sprite only and not the pivot point, like so:



Now if I run the same code, you will see that transforms are performed relative to this point instead of the middle:



This value can also be controlled in the Inspector.  It is called the offset and it is a value relative to the Node’s center point:



Or you can change the offset in code.  For example, to make the pivot the bottom left corner of the Sprite, you could do the following:

func _ready():

   var newOffset = Vector2(self.get_item_rect().size.width/2, -self.get_item_rect().size.height/2)


With the following result:



So, quick summary…  child Nodes are positioned relative to their parents and the top level node is the viewport.  All transformations happen relative to an objects offset, that offset is relative to the objects center which by default is the Node’s midpoint.


A Bit about Viewports


We should pause a bit to discuss the viewport, it’s a critical concept in graphics.  As you may notice in the earlier screenshots, the Viewport is drawn as a blue rectangle, with it’s top left corner at 0,0 in 3D space.  By default in Godot 2D, the root node is a viewport, which is why we could access it using get_parent() from our sprite node.  So, where exactly are this viewport’s dimensions set?  Good question!




In the Scene menu select Project Settings.  The following dialog appears ( this is where we set default scene earlier ):



These are your key viewport related settings.  Obviously width and height are what determine the dimensions of your viewport.  There are a few other key settings here too, such as resizable and fullscreen, that determine how the window works on a desktop computer ( these settings are meaningless on mobile devices ).  Orientation on the other hand is important to mobile devices ( landscape vs portrait or lengthwise vs widthwise ) but meaningless on PCs.  stretch_mode and stretch_aspect are useful for dealing with devices of differing resolutions, we will probably cover this in more detail in a separate posting.


Viewports are critical as they allow you to work across a number of different devices in different resolutions using the same basic code.


The Video Version



AppGameKit Studio

See More Tutorials on!

Month List