12. February 2015
THIS POST IS A WORK IN PROGRESS!

 

 

If you are doing C++ development these days there are a number of IDEs available to make your life a great deal simpler.  Some are cross platform, some are required to supported certain targets.  But not all IDEs are created equal, and opinions differ on whats good and what isn’t.  Since we spend so much of our time buried in our IDEs, its worthwhile finding the one that fits you best.

 

What follows is a roundup of the available C++ IDEs.  Please keep in mind, an IDE and a Compiler aren’t the same thing.  Many of these IDEs use the same compilers behind the scenes.  Or often, such as with the Android NDK, a different compiler all together.  IDE is all about productivity… code editing, debugging, refactor, project management, etc.

 

 

No IDE

 

Of course, you don’t need an IDE.  This is a bit more appealing on CLI focused operating systems like Linux or even MacOS.  While on Windows, even with Cygwin or Powershell, the command line just isn’t as nice of a place to live.  Of course even on Windows you can download gcc or another free C++ compiler and work however you wish.  Visual Studio also has a command line option.  It is important to realize you do not NEED an IDE at all, although I personally wouldn’t want to live without one, especially when it comes to debugging.

 

If you go the no IDE route, you are going to need to provide your own C++ compiler.  If you are on Linux or Mac, you most certainly already have gcc installed.  The following is a list of common available C++ compilers that are available outside of an IDE.

 

gcc -  Gnu C Compiler - The daddy, the heart of open source. — https://gcc.gnu.org

cygwin — Cygwin — Not a C++ compiler, but a Unix like distro for Windows.  Contains gcc mentioned above but for Windows

mingw — MingW — Mininmal Gcc for Windows.  As the name suggests, it’s a gcc port for Windows.

clang — Clang — Increasingly more popular than gcc.  This is the C/C++ front end for...

llvm — LLVM — think of LLVM like a compiler provider.  You generally, won’t work at this level.  See clang :)

Digital Mars — Digital Mars — They make D now, but before they made C++ compilers for a very long time.  Not sure why you’d pick though

Intel C++ — Intel C++ — Paid product, pretty specialized

Visual C++ — Used to be available stand alone, or in Platform SDK.  Sadly it is no longer, so 10GB download for you!

 

There are more, but those are the common compilers.  The majority use gcc or clang on MacOS and Visual C++ on Windows in case you were wondering.

 

Now, if you go the IDE-less route, you are probably going to want an editor of some form.  Here are a few of the more commonly chosen options:

Emacs — Want a text editor with a learning curve as high as a mountain but with functionality to match?

Vim — Because you can’t have a war without two sides!  Vim vs Emacs, fight! 

(Truth is, I personally recommend neither of the above, too steep learning curve, too archaic… but I aint going down that road!)

Sublime Text — It’s simply Sublime.  It actually is, incredibly well named and one of the first installs on a new system for me.

Notepad++  — Windows only, but a potent editor with great plugin support.  Not quite sublime, more of a swiss army knife

Notepad — ‘cause back in my day we walked 20 miles in the snow, uphill, in both directions!  Seriously, just don’t.

 

 

C++ IDE List


 

AppCode

 

https://www.jetbrains.com/objc/

Platforms

Mac Os

Price

$199

AppCode is an IDE from JetBrains, the maker of IntelliJ as well as the popular ReSharper refactoring software.  This isn’t strictly a C++ IDE, it’s more a better Xcode which in my humble opinion was desperately needed.  It’s for Objective C, Swift and C++ development.  C++ is certainly not the focus, however there is very good C++ support.  On top as you might expect there is good refactoring support.  There is also a nicely integrated debugger, good code completion and more.  If you are familiar with IntelliJ, AppCode will be immediately comfortable.  Jetbrain have also started making a C++ IDE, which we will discus momentarily.

Screenshots

 

CLion

 

https://confluence.jetbrains.com/display/CLION/Early+Access+Program

Platforms

Linux

Mac OS

Windows

 

Price

None yet.

 

NOTE!  Lion is currently an EAP — Early Access Preview.  Basically it’s a beta.

Another IDE from JetBrains, this one is dedicated 100% to C++ development.  This product is in early release and eventually will be commercial paid software.  The basic idea behind CLion is to provide a C++ IDE that works equally across all platforms. If you are familiar with out JetBrain products, CLion will be instantly comfortable.  CLion is built over top of the popular CMake build system, this can present some challenges when trying to import projects that do not use CMake as their build system.  Of course once again you can expect excellent refactoring support.  CLion is expected to hit v1.0 release in early Q1 2015.

Screenshots

Programming

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 http://www.freesound.org/.  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:

image

 

 

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:

image

 

Now drop it down again and select Edit:

image

 

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.

image

 

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:

image

 

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

image

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:

image

 

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:

image

 

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

image

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():
   play("siren")

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.

image 

image

 

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():
   pass


func _on_Button_pressed():
    get_tree().get_root().get_node("SamplePlayer").play("siren")

 

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:

image

 

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:

 

get_tree().get_root().get_node("SamplePlayer").play("siren",true)

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 = player.play("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:

image

 

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:

image

Now drop it down again and select Load:

image

 

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():
   self.play()

 

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:

image

 

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():
   set_process(true)
   song2 = load("song2.ogg")
   
func _process(delta):
   if(self.is_playing() != true):
      if(self.get_stream() == song1):
         self.set_stream(song2)
      else:
         self.set_stream(song1)
      self.play()

 

 

The Video Version

 

Programming , , ,

3. February 2015

 

In this next part in the ongoing LibGDX Video tutorial series, we take our final look at the Scene2D library.  Specifically we look at using Scene2D to provide a UI, including buttons, windows, layout containers and more.  We also look at how to mix “normal” and Scene2D games together. 

 

The video is available in full HD here.  The source code from the examples is below the video:

 

Example 1

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Dialog;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.Timer;
import com.badlogic.gdx.utils.viewport.ScreenViewport;

public class Scene2DUiDemo1 extends ApplicationAdapter {
   private Skin skin;
   private Stage stage;
   
   @Override
   public void create () {
      skin = new Skin(Gdx.files.internal("uiskin.json"));
      stage = new Stage(new ScreenViewport());

      final TextButton button = new TextButton("Click Me",skin,"default");
      button.setWidth(200);
      button.setHeight(50);

      final Dialog dialog = new Dialog("Click Message",skin);

      button.addListener(new ClickListener(){
         @Override
         public void clicked(InputEvent event, float x, float y) {
            dialog.show(stage);
            Timer.schedule(new Timer.Task() {
               @Override
               public void run() {
                  dialog.hide();
               }
            }, 10);
         }
      });
      stage.addActor(button);

      Gdx.input.setInputProcessor(stage);
   }

   @Override
   public void render () {
      Gdx.gl.glClearColor(0, 0, 0, 1);
      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
      stage.act(Gdx.graphics.getDeltaTime());
      stage.draw();
   }


}

Example 2

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.*;
import com.badlogic.gdx.scenes.scene2d.utils.Align;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.Timer;
import com.badlogic.gdx.utils.viewport.ScreenViewport;

public class Scene2DUiDemo1 extends ApplicationAdapter {
   private Skin skin;
   private Stage stage;

   private Table table;
   private TextButton startButton;
   private TextButton quitButton;
   
   @Override
   public void create () {
      skin = new Skin(Gdx.files.internal("uiskin.json"));
      stage = new Stage(new ScreenViewport());
      table = new Table();
      table.setWidth(stage.getWidth());
      table.align(Align.center | Align.top);

      table.setPosition(0,Gdx.graphics.getHeight());
      startButton = new TextButton("New Game",skin);
      quitButton = new TextButton("Quit Game",skin);

      table.padTop(30);

      table.add(startButton).padBottom(30);

      table.row();
      table.add(quitButton);

      stage.addActor(table);
      Gdx.input.setInputProcessor(stage);
   }

   @Override
   public void render () {
      Gdx.gl.glClearColor(0, 0, 0, 1);
      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
      stage.act(Gdx.graphics.getDeltaTime());
      stage.draw();
   }


}

 

Example 3

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.RepeatAction;
import com.badlogic.gdx.scenes.scene2d.ui.*;
import com.badlogic.gdx.scenes.scene2d.utils.Align;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.Timer;
import com.badlogic.gdx.utils.viewport.ScreenViewport;

public class Scene2DUiDemo1 extends ApplicationAdapter implements InputProcessor {
   private Skin skin;
   private Stage stage;

   private Table table;
   private TextButton startButton;
   private TextButton quitButton;

   private SpriteBatch batch;
   private Sprite sprite;
   
   @Override
   public void create () {
      skin = new Skin(Gdx.files.internal("uiskin.json"));
      stage = new Stage(new ScreenViewport());
      table = new Table();
      table.setWidth(stage.getWidth());
      table.align(Align.center | Align.top);

      table.setPosition(0,Gdx.graphics.getHeight());
      startButton = new TextButton("New Game",skin);
      quitButton = new TextButton("Quit Game",skin);

      startButton.addListener(new ClickListener() {
         @Override
         public void clicked(InputEvent event, float x, float y) {
            Gdx.app.log("Clicked button","Yep, you did");
            event.stop();
         }
      });

      table.padTop(30);

      table.add(startButton).padBottom(30);

      table.row();
      table.add(quitButton);

      stage.addActor(table);



      batch = new SpriteBatch();
      sprite = new Sprite(new Texture(Gdx.files.internal("badlogic.jpg")));
      sprite.setSize(Gdx.graphics.getWidth(),Gdx.graphics.getHeight());

      Timer.schedule(new Timer.Task() {
         @Override
         public void run() {
            sprite.setFlip(false,!sprite.isFlipY());
         }
      },10,10,10000);


      // ORDER IS IMPORTANT!
      InputMultiplexer im = new InputMultiplexer(stage,this);
      Gdx.input.setInputProcessor(im);
   }

   @Override
   public void render () {
      Gdx.gl.glClearColor(0, 0, 0, 1);
      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

      batch.begin();
      sprite.draw(batch);
      batch.end();

      stage.act(Gdx.graphics.getDeltaTime());
      stage.draw();
   }


   @Override
   public boolean keyDown(int keycode) {
      return false;
   }

   @Override
   public boolean keyUp(int keycode) {
      return false;
   }

   @Override
   public boolean keyTyped(char character) {
      return false;
   }

   @Override
   public boolean touchDown(int screenX, int screenY, int pointer, int button) {
      sprite.setFlip(!sprite.isFlipX(),sprite.isFlipY());
      return true;
   }

   @Override
   public boolean touchUp(int screenX, int screenY, int pointer, int button) {
      return false;
   }

   @Override
   public boolean touchDragged(int screenX, int screenY, int pointer) {
      return false;
   }

   @Override
   public boolean mouseMoved(int screenX, int screenY) {
      return false;
   }

   @Override
   public boolean scrolled(int amount) {
      return false;
   }
}

 

uiskin.json

// @formatter:off
{
  com.badlogic.gdx.graphics.g2d.BitmapFont: { default-font: { file: Razer.fnt } },
  com.badlogic.gdx.scenes.scene2d.ui.TextButton$TextButtonStyle: {
   default: { down: default-round-down, up: default-round, font: default-font },
  },
  com.badlogic.gdx.scenes.scene2d.ui.Window$WindowStyle: {
    default:  {
      titleFont: default-font
     }
   }
}

Programming , , ,

1. February 2015

 

Today I ran into something extremely annoying while typing some JSON for a LibGDX tutorial.  LibGDX uses a naming convention that IntelliJ doesn’t like…  here, I’ll show you what I mean.

 

codeReform

 

Suffice to say… it’s pretty annoying.  What’s even more annoying is there is simply no way to turn this behavior off.  There is however a way to suppress it thankfully.  It isn’t intuitive however, so I figured I would make this post.  So hopefully if you are struggling with turning off IntelliJ automatic code reformatting in JSON, this will be useful to you.

 

Go to File->Settings… menu.  Locate Editor->Code Style settings.   Find “Formatter Control” and tick Enable Formatter markers in comments. 

image

 

Now add // @formatter:off at the top of your file and edit like normal.   Now…

 

codeReform2

 

Much better!

General, Programming ,

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() {
   
   setupApplication()
   scene = createScene()
   
   while(!quit){
      get_input()
      update_physics()

      scene.updateAllChildren()
      scene.render()
   }
}

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():
   self.set_process(true)
   
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
   self.set_pos(cur_pos)

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:

 

Video_2015-01-27_105150

 

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):
   if(Input.is_key_pressed(KEY_ESCAPE)):
      if(Input.is_key_pressed(KEY_SHIFT)):
         get_tree().quit()

 

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):
   if(Input.is_mouse_button_pressed(BUTTON_LEFT)):
      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():
   set_process_input(true)

 

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):
         self.set_pos(Vector2(event.x,event.y)) 
         
   # on keyboard cursor key
   if(event.type == InputEvent.KEY):
      var curPos = self.get_pos()
      
      if(event.scancode == KEY_RIGHT):
         curPos.x+= 10
         self.set_pos(curPos)

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

 

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):
      self.get_tree().set_input_as_handled()
      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():
   set_process_unhandled_input(true)

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…

image

 

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

image

Then click Add

image

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

image

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

image

 

You will then be prompted to press a key:

image

 

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

image

 

Your Input Map should now look something like this:

image

 

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):
   if(Input.is_action_pressed("MOVE_RIGHT")):
      var cur_pos = self.get_pos()
      cur_pos.x += 1
      self.set_pos(cur_pos)

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):
   
   if(event.is_action("MOVE_RIGHT")):
      self.set_pos(Vector2(0,0))

 

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.

 

THIS IS COMPLETELY OPTIONAL!

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;

   frame+=ticks_elapsed;

   last_ticks=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)
      step=frame_slice*8;

   time_accum+=step;

   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();

      PhysicsServer::get_singleton()->sync();
      PhysicsServer::get_singleton()->flush_queries();

      Physics2DServer::get_singleton()->sync();
      Physics2DServer::get_singleton()->flush_queries();

      if (OS::get_singleton()->get_main_loop()->iteration( frame_slice*time_scale )) {
         exit=true;
         break;
      }

      message_queue->flush();

      PhysicsServer::get_singleton()->step(frame_slice*time_scale);
      Physics2DServer::get_singleton()->step(frame_slice*time_scale);

      time_accum-=frame_slice;
      message_queue->flush();
      //if (AudioServer::get_singleton())
      // AudioServer::get_singleton()->update();

      fixed_process_max=MAX(OS::get_singleton()->get_ticks_usec()-fixed_begin,fixed_process_max);
      iters++;
   }

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

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

   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
            OS::get_singleton()->frames_drawn++;
         }
      } else {
         VisualServer::get_singleton()->draw(); // flush visual commands
         OS::get_singleton()->frames_drawn++;
         force_redraw_requested = false;
      }
   } else {
      VisualServer::get_singleton()->flush(); // flush visual commands
   }

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

   for(int i=0;i<ScriptServer::get_language_count();i++) {
      ScriptServer::get_language(i)->frame();
   }

   idle_process_max=MAX(OS::get_singleton()->get_ticks_usec()-idle_begin,idle_process_max);

   if (script_debugger)
      script_debugger->idle_poll();


   // x11_delay_usec(10000);
   frames++;

   if (frame>1000000) {

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

      OS::get_singleton()->_fps=frames;
      performance->set_process_time(idle_process_max/1000000.0);
      performance->set_fixed_process_time(fixed_process_max/1000000.0);
      idle_process_max=0;
      fixed_process_max=0;

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

         //PerformanceMetrics::print();
      };

      frame%=1000000;
      frames=0;
   }

   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() {

   ObjectTypeDB::bind_method("input_event",&MainLoop::input_event);

   BIND_CONSTANT(NOTIFICATION_WM_FOCUS_IN);
   BIND_CONSTANT(NOTIFICATION_WM_FOCUS_OUT);
   BIND_CONSTANT(NOTIFICATION_WM_QUIT_REQUEST);
   BIND_CONSTANT(NOTIFICATION_WM_UNFOCUS_REQUEST);
   BIND_CONSTANT(NOTIFICATION_OS_MEMORY_WARNING);

};

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

   init_script=p_init_script;
}

MainLoop::MainLoop() {
}


MainLoop::~MainLoop()
{
}



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


}

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

   if (get_script_instance())
      get_script_instance()->call("input_event",p_event);

}

void MainLoop::init() {

   if (init_script.is_valid())
      set_script(init_script.get_ref_ptr());

   if (get_script_instance())
      get_script_instance()->call("init");

}
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()) {
      get_script_instance()->call("finish");
      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:

image

 

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

 

Programming , , ,

Month List

DisqusCommentsSummary