Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

12. September 2016

 

Welcome to the next part in our ongoing Defold Game Engine tutorial series.  Today’s tutorial is going to show an area where the Defold engine really shines, creating 2D tile based levels.  This way of creating levels is to paint levels in a data structure called a tilemap, which itself is a collection of tiles.  A tile is simply a portion of an image that can be drawn over and over, much like you could use Lego blocks to create a castle.

 

As always there is an HD video version of this tutorial available here.

 

For this tutorial we need a tileset to work with.  This is simply an image composed of tiles, in this case with no spaces or padding between them.  I personally am using the tiles from opengameart.org in the Free Platformer Game tileset.  I have taken these individual tiles and merged them together into a single image you can download below.  (Be sure to click the image to get the full sized version.  In this example size does matter! ).

 

tilesThis is a 1024x512 pixel image composed of 64x64 pixel tiles.  Of course you can use whatever image you want, just be aware that if there is padding or different sized tiles your version is going to be different.

 

As always I assume you have gone through the prior tutorials in the series.  Alright, now that we are set up, let’s get going.

 

Creating a Tile Source

 

First things first, we need to create a directory for our level, tiles, images, etc.  I simply created a folder called level.  Inside this folder I created a directory called images and dragged the image above into that folder, like so:

image

 

Now we need to create a tile source.  You can think of this as the palette or selection of tiles we are going to paint with.  Don’t worry, it’s exceedingly easy.  Simply right click level, select New->Tile Source File

image

 

Called it tiles.tilesource like so:

image

 

Now in Outline make sure Tile Source is selected:

image

 

Now in the Properties panel, select the image file we added earlier for the Image property, then set Tile Height and Tile Width to 64.  Obviously if you used a different image you may have different settings here.

image

 

Now in your viewport you should see your tiles, with the grid drawn nicely around them like so:

image

 

All done creating our tilesource.  Make not of the collision property... we will come back for that in the next tutorial.  Make sure you save.

 

Creating a Tile Map

Now it’s time to actually create our tile map.  Once again right click the level folder and select New->Tile Map File.  Name this one map.tilemap:

image

 

Now in Outline make sure Grid is selected:

image

 

Now in the properties, pick out tilesource:

image

 

Now select layer1 in the outline window and we can begin painting!

 

In the viewport use the spacebar to bring up the tile source, then left click to select the active tile.  Now hit space again to hide the tile source and paint using the left mouse button.  You can also use the right mouse button to select multiple painted tiles to easily clone and reproduce compound tiles.

GIF2

 

If you need to paint tiles on top of other tiles, simply create another layer, right click Layers and select add:

image

 

The z order determines the draw order of tile layers:

image

 

Right click an empty space then left click to delete a tile if required.  Save before continuing on!

 

Using a Tile Map

Finally it’s time to put our newly created tilemap to use.  This is also simple.  Open your main.collection in the editor then add a new game object just like we did in the past.  Right click the game object and select Add Component From File:

image

 

Select your .tilemap file, and voila:

image

 

The Video

Design, Programming ,

9. September 2016

 

Never in the history of game development have indie developers, or developers in general, had access to such a massive array of resources.  What is perhaps most impressive is that so many of these tools are available at no cost.  That is exactly what this guide is going to look at, and end to end look at freely available tools for all facets of game development. 

There is also a video version of this guide available here.

This guide is not meant to be comprehensive, I don’t want to flood the reader with too much choice.  I do however want to make sure I capture the “greatest hits”, so If I miss a package that you believe should have been included, please let me know!

 

The Definition of Free

First off, this point needs to be addressed right up front.  To use a popular open source expression, I am talking free as in beer, not free as in freedom.  This means that non-open source tools are going to be included, although when source is available I well mention.  The primary criteria is that the developer can get started and develop using the tool completely free.  There might however be a cost after a certain revenue threshold is met (I find this to be an exceedingly fair business model personally) or there might be multiple tiers available, so long as it includes a free tier that enables you to ship and sell your title, it will be eligible for this guide.  It will also include software and tools that have a premium version available, just know that I am referring to the free tier in this guide.

 


Art

In this section we will look at the essential tools for creating game development art, both 2D and 3D.

 

2D

There are a wide variety of 2D imaging applications available, some specialized for developing and animating 2D game sprites, while others are more general purpose image manipulation applications or painter focused.

 

Paint.Net – Windows

An excellent, easy to use general purpose Painting application with hundreds of plugins available, layer support and more.  Frankly this is my goto application for simple image manipulation tasks.  Featured Paint.NET in the GameDev Toolbox series if you want to learn more.  Sadly it is Windows only software.

 

GIMP – Various – Open Source

Pretty much the closest thing to an open source alternative to Photoshop.  It’s a powerful application with an unwieldy UI.  Thankfully they have been focusing heavily on making UI improvements.

 

Inkscape – Various – Open Source

Inkscape is different from other applications on this list as it’s Vector based (instead of bitmap/raster based).  It takes an approach similar to Adobe Illustrator or Flash and is very useful for creating resolution independent graphics.

 

Krita – Linux/Mac/Windows – Open Source

Krita is an open source application that is focused on digital painting, similar to commercial products like Corel Painter.  In recent releases however it has been extended to add animation and text support, making it more and more useful for game development.

 

ASESprite – Windows/Mac/Ubuntu

This is app is dedicated to creating and animating 8/16bit style sprites.  Supporting painting, layers, onion skinning, fixed color pallet, sprite sheet generation and more.

 

GratfX2 – Various – Open Source

Once upon a time there was a program called Deluxe Paint and it was responsible for art creation for 99% of games developed.  GrafX2 is an open source implementation of that application.

 

Piskel – Mac/Linux/Windows/Web – Open Source

Piskel is another pixel art oriented image editor, although this one is somewhat unique in being usable in the browser, with offline versions available for download.  Supports layers, palletes, animation frames and more.

 

JPixel – Various

Not technically free, it’s a name your own price application, however that price can be $0.  It’s a pixel art application with support for animations, tilesets, color palettes and more.

 

GraphicsGale – Windows

The free version of this application is mostly just limited in what file formats it supports for export.  Sadly it is Windows only.  Offers pretty much every feature you would expect from a pixel graphics oriented application.

 

ShoeBox – Adobe Air

ShoeBox is an image/sprite/texture manipulation tool.  Useful for creating textures from existing images, extracting an animation into a sequence of sprites, creating 9patch images and more.  This is a utility and not a graphics creation package like many in this list.  It requires the Adobe Air runtime to run.

 

TexturePacker – Mac/Windows

TexturePacker by Code and Web is a utility designed to create sprite sheets.  Like ShoeBox above it is not an image creation or modification application.  There is a free version but limits some advanced features.

 

DragonBones – Windows/Mac

Unique in this list, DragonBones is a 2D animation system that enables you to use bone based IK animation to control and animate 2D images.  It’s similar in function to Creature, Spriter and Spine but is completely free.  It comes with runtimes for playing your animations in various game engines.

 

OpenToonz – Windows/Mac

An open source implementation of Toonz, originally developed by Studio Ghibli and used to help make Princess Mononoke, is completely free to use.  Aimed primarily at film animations, Toonz has been used to create animation for games in the past.  Not an easy tool to master.

 

TileCraft – Windows/Mac/Linux – Open Source

TileCraft is a unique little tool for creating 2D sprites using a 3D workflow.  Essentially you add and subtract solid 3D shapes to create more complex 2D images.  It’s an interesting approach and is open source, but sadly hasn’t been updated in over a year.

 

3D

 

Blender – Most Platforms – Open Source

Blender is certainly the biggest 3D package available for free, it’s also open source and remarkably full featured.  Model, sculpt, animate, physics simulation, render and composite all using a single program.  There is a ton of power here, but also a huge learning curve.  Thankfully, I’ve got you covered with a pair of tutorial series.

 

Daz Studio – Windows/Mac

Daz Studio is a 3D package, focused heavily on characters.  It’s incredibly easy to use, is available for free, while they make money selling 3D models, outfits, etc.  It is similar in scope and functionality to another application called Poser, which is not available in a free form.  A warning however, they will spam the email address you register with.

 

Dilay – Windows/Linux – Open Source

Dilay is a free open source 3D sculpting tool in the same vein as Mudbox, Sculptris and ZBrush.  I featured Dilay in this video if you wish to learn more.

 

MagickaVoxel – Windows/Mac

MagickaVoxel is a free to use Voxel editor.  Voxels are an alternative to traditional polygon approach to models, essentially composing objects out of blocks in 3D space. Minecraft is the most famous Voxel based game, but there are plenty of other examples preceding Minecraft.

 

Mixamo/Mixamo Fuse – Windows

Mixamo is a gigantic animation data base, and set of tools for applying animations to 3D models.  Mixamo FUSE is a 3D character creator, using a video game like interface for making 3D character models.  It was purchased by Adobe and currently is available for completely free.  I reviewed Fuse before the Adobe acquisition if you want an idea of what you are getting.  This is perhaps the simplest way to create 3D character models and is certainly the easiest way to animate them.

 

PolyBrush – Windows

PolyBrush is a one of a kind 3D sketching app, enabling you to create complex organic 3D shapes using a sketching workflow.  There is a free version available with some limitations ( single layer, max 8 undo levels, cannot save brushes ) but it is perfectly functional.  I featured Polybrush in this video should you wish to learn more.

 

Sculptris – Windows/Mac

A free 3D sculpting tool from Pixologic, the makers of ZBrush.  It’s not actively developed anymore, but is a great introduction to sculpting and the results can be exported for use in other software such as Blender.  For more details you can watch our Scultpris feature in the GameDev Toolbox series.

 

Wings 3D – Most Platforms – Open Source

Wings is an excellent 3D modeling application built around the Winged Edge polygon.  It enables fast and fairly easy 3D model creation.  Development however appears to have stopped sadly.  In recent years the 3d modeling tools in Blender have also improved greatly, making Wings less and less valuable.

 


Audio

By far my weakest area of knowledge, the following are applications freely available and used to create and edit audio from sound effects to background music.

 

Audacity – Windows/Mac/Linux – Open Source

Audacity is the swiss army knife for recording, translating and modifying audio files.  Simply put you should stop everything and download this tool if you haven’t done so already.  Audacity was featured in the GameDev Toolbox series if you want more information.

 

SunVox – Various

SunVox is a class of program called a ModTracker and can be used to create music.  The interface is simply daunting, but the effects can be pretty amazing.  Runs on just about every platform created by man and possibly aliens.  Was featured in the GameDev Toolbox series as well.

 

ChipTone – Web

ChipTone is like a streamlined version of SunVox that runs in your browser.  Comes with several game focused samples and the ability to record your own.

 

Bfxr.net – Web

A web based sound fx generator.  Very easy to use, start with several default sounds ( explosion, laser, etc. ) then modify the generator to create exactly the effect you need, then download locally.  Dead simple.

 

FMod – Windows/Mac

FMod is perhaps the most used game middleware for AAA and A game titles.  While it’s commercial software, it’s free to use if make less than $100K USD a year. They also offer FMod.io that gives access to a gigantic library of sound effects for 99cents each.  There is a first look video of FMOD.io available here.

 

Podium Free – Windows

Podium is a surprisingly full featured free version of Podium.  Podium is a digital audio workstation (DAW) that enables you to create, record and edit audio and MIDI as well as hosting VST instruments and effect plugins.

 


 

Code

 

This is where the various programming languages and development tools are listed.  Just a few years ago many of these products cost many hundred or thousands of dollars.  These days most programming tools are made available for basically free.  This features only the languages and tools most commonly used in game development.  There are dozens of programming languages and literally hundreds of tools, so a line in the sand must be made.

 

Please note, you often don’t require a programming language at all, at least not a stand alone one.  It’s increasingly common for many game engines to include the entire tool-chain for you, basically hiding this layer from you.  Additionally, some may find using an IDE as way too heavy.  Don’t worry however, you can also work entirely from the command line or terminal and use a lighter weight code editor should you prefer.

 

Languages and IDEs

 

Visual Studio Community – Windows

Visual Studio Community is perhaps the most used IDE (Integrated Developer Environment) in the world of both Windows development and game development in general.  It includes several programming language, but C++, JavaScript and C# are the most commonly used for game development (VB.Net, F# and TypeScript are also supported).  It also contains editors, debuggers, source control and much more.  In fact it contains so much more it’s actually rather bloated at this point, resulting in an install size north of 10GB.  Visual Studio Community is a revenue/team size limited version of the full Visual Studio package.  It’s essentially the same product and for individuals there is no limitation, for organizations there is a team size limit of 5 developers and $1M USD in revenue.  For Enterprise organizations, usage is not permitted.  You can read the full license details here.

One recent change with Visual Studio is Microsoft recently acquired Xamarin, and made it’s suite of products available free as part of Visual Studio Community.  This now gives you the ability to target iOS and Android using Visual Studio and C#. 

 

XCode – MacOS

XCode is the Apple equivalent of Visual Studio and is a requirement to sign and package iOS applications.  It can be used to develop for the various Apple platforms ( OS X, iOS, AppleTV, etc. ) with the primarily languages being Objective C and now Swift.  C++ is also fully supported, but is treated like a bit of a red headed stepchild for some unfathomable reason.  Like Visual Studio it contains a full set of development tools including code editors, an integrated debugger, forms designers and more.  XCode used to require a developer subscription with Apple but this requirement and fee has now been removed.  On a personal note, I’d rather use my forehead as a hammer than use XCode, but that’s just me.

 

GNU Tool Chain – Various – Open Source

GCC, or the GNU compiler collection, is a set of open source developer tools including support for just about every single language you’ve ever dreamed of using.  If you are developing on Linux, chances are you already have much of the GNU toolchain installed.  One caveat of the GNU suite is the GPL or Gnu Public License.  This open source license greatly restricts what you can do with the software, basically requiring you to make all changes and modifications to the code open and available.  Don’t worry, this restriction only applies to changes to tools themselves, not code you compile using them.  As mentioned earlier, GCC is generally included with any Linux distribution.  There are also ports to various platforms such as MingW for Windows or MacPorts on Windows.  Keep in mind GCC is NOT an ide, it’s the underlying compiler/linker/debugger.  Generally some form of editor is required as well.

 

LLVM(Clang) – Various – Open Source

LLVM, which isn’t actually an acronym no matter what other people tell you, is a suite of tools very similar to GCC.  It is instead released under the much more liberal BSD license and is the underyling technology behind a lot of commercial tools as a result, including XCode mentioned earlier, as well as closed development kits, such as the PlayStation 4.  An LLVM implementation is available as part of the MingW port, while it can also be used directly inside Visual Studio.  Like GCC, this is a lower level suite of tools and generally still requires an editor for code creation.

 

Qt Creator – Windows/Mac/Linux

Qt Creator is a full cross platform IDE primarily for C++ programming.  It’s has several tools designed to work with the Qt cross platform UI toolkit, but can be used as a standalone C++ development environment.  It includes a code editor, debugger, project management tools, UI designers, etc just like VS and XCode.

 

JetBrain’s Suite Of Products – Most Platforms

Instead of listing each product individually, it’s probably easier to mention the entire suite.  Most of the IDEs made by JetBrain offer a free version that is generally enough for most developers needs.  Perhaps their most known product is IntelliJ IDEA a Java IDE that has plugin support for dozens of programming languages.  They also have C#, C++, HTML/JavaScript, Python, etc. IDEs available as well.  

 

Eclipse – Most Platforms

Primarily a Java IDE, plugins have extended it’s functionality to support several other languages.  Full suite of tools and used to be the preferred development path for Android development (it is no longer).  Eclipse has everything and the kitchen sink.  Personally I’d rather code using morse code then use Eclipse again, but I figured I’d mention it for completeness.

 

Netbeans – Most Platforms

Oracle’s Java IDE, but can add support for other languages via plugins.  Again full featured, but certainly enterprise focused.  I’d prefer it to Eclipse, but then, I’d prefer just about anything to Eclipse.

 

Other Languages of Note:

 

Special Note for Android Developers

Android is a bit of a special case for development.  While based on Java, it’s not technically using Java (it’s a long story and got Google sued).  So long and short of it, there are special tools for Android development, specifically the Android SDK(Java) and the Android NDK(C++).  Google also make an IDE called Android Studio available, a port of the IntelliJ IDE, specifically for IDE development.

 

Editors

The following are code oriented text editors.  Don’t want the heavy install of a full IDE, are using a game engine that doesn’t include it’s own editor (or it’s built in editor sucks?), then you will probably want one of these.  Each of the following generally offer most of the following: multiple language support, plugin extensibility, syntax highlighting, refactoring tools and more.  Choosing the right editor is a deeply personal experience... Im not going to start any wars here... just list the options available... you pick your favorite.

And just so I don’t fend the old timers...

Just be aware of the learning curve, you will need to memorize about a hundred character combinations to become proficient with either of these editors.  That said, once you’ve got them down they can be exceedingly efficient.  It’s worth noting however the VI and Emacs keyboard bindings are often available in other editors.  A quick note here, Visual Studio Code and Visual Studio Community have NOTHING in common.  Code is a light weight cross platform editor, not a Windows only IDE.

 


 

Tools and Misc

Didn’t fit somewhere else but is available for free?  It goes here.

 

Tiled – Windows/Linux/Mac – Open Source

The preeminent free 2D map editing software package.  The map files Tiled generates are supported by just about every game engine available.  We have a full Tiled tutorial series available if you wish to learn more.

 

FreeMind – Various – Open Source

Freemind is an open source mind mapping package.  If you’ve never used one before, this is a great way to get ideas from your head to your computer.  There are actually a massive number of mind mapping packages available, FreeMind just happens to be the one I’m most familiar with.

 

ShaderToy – Web

GPU Shaders are becoming more and more critical to the world of game development and ShaderToy is perhaps the primary place to share and download shaders on the web.  You can also modify the shader source and see the results in real time.  Almost 12,000 shaders currently exist in the collection and growing daily.

 

FreeSound.org – Web

A huge collection of free audio files.

 

OpenGameArt.org – Web

A massive collection of free game graphics.

 

VST4Free.org – Web

A resource for VST instruments and effects.  VST stands for Virtual Studio Technology an enables you to encode samples of actual instruments, special sound effects etc. and use them in VST compatible instruments and software such as Podium mentioned earlier.

 


Game Engines

This is a section that could fill a few hundred pages and only just get started.  The reality is, almost every single game engine is available in a free form with differing business models.  Some such as Unreal Engine take a percentage of your revenue after certain thresholds are exceeded.  Others like Unity offer a free tier which has limitations, such as a maximum annual revenue, and require a subscription if you exceed those amounts.  There are also game engines like Godot, Urho, Atomic and Panda that are completely free and open source.  Then there are all the various frameworks such as SFML, LibGDX, SDL, Love, etc. many of which are open source and freely available.

 

This topic is well beyond this guide’s ability to cover.  Thankfully I’ve slowly been reviewing many of these engines and frameworks as part of the Closer Look series.

 


The Video

 

Design, Art, General, Programming , ,

24. August 2016

 

Welcome back to the ongoing Defold Game Engine tutorial series looking at all aspects of game development using the Defold game engine.  In this tutorial we are going to look at the process of playing sound and music in Defold.

 

There is an HD video version of this tutorial available here.

 

Playing sound in the Defold engine is simple, which is a double edged sword.  It’s extremely easy to add and play a sound file.  On the other hand the functionality provided is also quite simple.  Many things you may want to accomplish ( callback on sound end, fast forwarding/rewinding a playing audio file, positional audio, etc. ) simply aren’t supported.

Let’s start by adding some audio files to the project.  In my case I added a folder named audio and dragged in an ogg file and a wav file from Windows Explorer to Defold.  These are the two file formats supported.  The ogg file is an Ogg Vorbis file, a compressed streamed format similar to mp3 format but not patent encumbered.  Wav files are almost entirely uncompressed but require less processing power.  In a nutshell for longer form audio files, such as music, use an ogg.  For sound effects, use wav.  The end result should look something like:

image

 

Next we go ahead and create a sound component for our game.  You could parent your sound components to whatever game object you wish.  If it makes sense to create a music player game object and attach all the sounds to it, you could.  Or if you want your game objects (for example, the player) to own their own sound components, that’s alright too.  Select whatever game object you want to add the sound to, right click and select Add Component.

image

 

Next select Sound from the component list.

image

 

Here I am creating one for the music file first:

image

 

Hit the … button beside Sound and select the ogg file you dropped in earlier.  Notice in this case I changed the Group to music.  I repeat the same process for the wav file, instead named sfx. 

 

Now playing the sound effect using code is extremely easy and once again uses messages like so:

msg.post("#music","play_sound")

 

Simply post the play_sound message to the music component of our current game object.  Playing the sound effect file is the exact same process but instead post the message to the #sfx component like so:

msg.post("#sfx","play_sound")

 

We can also control the volume of the sound component, like so:

msg.post("#music","set_gain", { gain = volume })

 

Volume is a value from 0.0 to 1.0, where 0.0 is no volume, while 1.0 represents full volume.  Remember earlier when I changed the group for our music file from “master” to “music”.   Groups enable you to control several sound effects at once, for example muting all the playing songs or sound effects.  For example, we could mute all the sounds in the group music with the following call:

sound.set_group_gain(hash("music"), 0.0)

 

Here is the full source for this example:

-- Local variable for volume. 0 is none, 1 is full
local volume = 1.0

function init(self)
  msg.post(".","acquire_input_focus")
  -- start playing the background music
  msg.post("#music","play_sound")
end

function on_input(self, action_id, action)
  if(action_id == hash("SPACE_PRESSED") and action.pressed == true) then
    -- if user hits the spacebar play the soundfx file. 
    -- multiple presses will play multiple instances.
    msg.post("#sfx","play_sound")
  elseif(action_id == hash("ESC") and action.pressed == true) then
    -- on ESC mute the entire group "music"
    sound.set_group_gain(hash("music"), 0.0)
  elseif(action_id == hash("DOWN_ARROW") and action.pressed == true) then
    if volume >= 0 then
      volume = volume - 0.1
    end
    -- lower the volume of our music
    msg.post("#music","set_gain", { gain = volume })
  elseif(action_id == hash("UP_ARROW") and action.pressed == true) then
    if volume <= 1 then
      volume = volume + 0.1
    end
    -- increase the volume of our music
    msg.post("#music","set_gain", { gain = volume })    
  end
end

 

The Video

Programming

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:

image

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

image

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:

image

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.

image

 

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.

image

 

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

image

 

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.

 

Scripting

 

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:

image

 

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:

image

 

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)
  msg.post(".","acquire_input_focus")
end

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

 

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. 

image

 

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

image

 

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:

image

 

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

image

 

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)
  msg.post("main:/character", "marco", { msg = "You out there?", meaningOfLife = 42 })
end

 

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:

image

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:

image

 

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)
  pprint(message)
    if(message_id == hash("marco")) then
      print("Polo")
  end
end

 

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:

image

 

So we could easily change the background color sending a message valued clear_color to @render like so:

msg.post("@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.

 

Properties

 

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:

image

 

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:

go.property("MyProperty",42)

To the top of the script file.

f you are wondering just where the heck go.property() 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:

print(self.MyProperty)

 

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:

image

 

The Video

Programming

7. August 2016

 

I’ve been a huge fan of the open source Godot Engine for a very long time, in fact I’ve done an in-depth tutorial series available here.  Godot has seen a number of improvements in the upcoming 2.1 release, but the recently added Visual Scripting interface is probably the biggest new addition.  In this post we are going to look at this new functionality.  A couple of warnings to start.  First, as of writing ( 8/7/2016 ), Visual Scripting is only available in the development branch.  So you will have to build Godot engine from scratch from the Github repository.  Second, this functionality is extremely early and not fully developed.  There is currently no debugger or profiler support and expect bugs.  Heck, I’m having trouble even running scripts at this point, but it’s probably user error on my end.  You have been warned!

 

I also did a video showing hands on with the new Godot Visual Scripting language.  It is available embedded below.

 

Creating a Visual Script

 

Creating a script is a simple process, basically identical to creating a GDScript.  Add a new script as usual.

image

 

Now in the Create Node Script, pull down language and select VisualScript.  VisualScript’s have a .vs extension in Godot.

image

 

Creating Visual Scripts

 

Visual Scripts are basically a flow chart of nodes, like so:

 

image

 

You start by implementing a function.  All of the usual GDScript functions are here:

image

 

This enables you to handle various events within your games lifecycle.  This will create a new node on the graph that acts as an entry point:

image

 

You notice in this example there is a parameter “event” here.  With it selected you can see it’s values in Inspector:

image

 

You will notice on the right side of the Function node there is an arrow and blue dot.  The arrow is for program flow, while the dot represents output.  Other nodes can have various inputs, which are also color coded.  We can now add other nodes to our graph, from the Available Nodes section.

image

There is basically a one to one ratio of nodes and functions available in GDScript.  Add a new Node from the InputEvent section for Is Pressed, simply drag and drop from the Available Nodes to the drawing surface.  Now we connect the two nodes together.

GIF

 

You will notice the newly created is_pressed test has another line out to continue the process as well as a bool output (notice the different color coding).  We could not continue our code by branching to a conditional like so:

image

 

Of course, this is VERY early, but it does give you an idea of how Visual Scripting will work in Godot.

 

The Video

Programming

Month List

Popular Comments