Subscribe to GameFromScratch on YouTube Support GameFromScratch on Patreon

17. March 2017

 

Now that we have covered getting your development environment up and running, we are going to jump into our first HaxeFlixel application.  Let’s start from the very beginning and create a new application.  As mentioned in the Getting Started tutorial, we can create an application using the simple command:

flixel tpl –n “HelloWorld”

This creates a directory with a skeleton application to get us started.  It actually creates a bit more code then we need, we are going to strip it down to just two source files.

image

 

It is pretty much tradition to make your first program a simple Hello World application, so that is what we are going to do.  We will simply print the text “Hello World” on screen, but since this is ultimately a game we are creating here, we will also animate it!  Ok, code time, let’s start with Main.hx, the entry point of our application.  Here is the source code:

import flixel.FlxGame;
import openfl.display.Sprite;

class Main extends Sprite
{
   public function new()
   {
      super();
      addChild(new FlxGame(0, 0, GameState));
   }
}

 

One thing that might immediately seem awkward is that our Main class inherits from Sprite.  This is a throwback to the Flash development world, just think of a Sprite as “something that is visible on screen”.  When our Main object is created it’s constructor is called and really it does just one thing, creates a new FlxGame object passing our GameState class in as a parameter.  The first two parameters to the FlxGame constructor are the width and height of our game window.  In this case we didn’t specify a value, meaning the value from the Project.xml file will be used instead.  If you look at Project.XML (which was generated for you) you will see the lines:

   <!-- ____________________________ Window Settings ___________________________ -->

   <!--These window settings apply to all targets-->
   <window width="640" height="480" fps="60" background="#000000" hardware="true" vsync="true" />

   <!--HTML5-specific-->
   <window if="html5" resizable="false" />

   <!--Desktop-specific-->
   <window if="desktop" orientation="landscape" fullscreen="false" resizable="true" />

   <!--Mobile-specific-->
   <window if="mobile" orientation="landscape" fullscreen="true" width="0" height="0" />

Due to this configuration by default our application will have a resolution of 640x480, while on mobile devices we will instead use the full screen.  As you can see it’s possible to set multiple definitions using the if=”platform” conditional.  If you want to have FlxGame create a larger or smaller window you can either specify the value when creating your FlxGame object, or you can change it’s value in the <window> tag.  Ok, back to our code...

As mentioned earlier, we created a FlxGame object, which is the heart of your application and contains the game loop.  Every single game or game engine has a game loop in some form, it’s essentially a loop that runs over and over until your game is done and is responsible for polling input, updating the world and drawing graphics on screen.  We don’t actually use FlxGame directly however, our game is instead broken into multiple states.  We see this in action in GameState.hx, here is the source:

import flixel.FlxG;
import flixel.FlxState;
import flixel.text.FlxText;
import flixel.util.FlxColor;

class GameState extends FlxState
{
   var text:FlxText; 
   override public function create():Void
   {
      super.create();
      text = new FlxText(0,0,FlxG.width,"Hello World",64);
      text.setFormat(null,64,FlxColor.RED,FlxTextAlign.CENTER);
      add(text);
   }

   override public function update(elapsed:Float):Void
   {
      super.update(elapsed);
      text.y ++;
      if ( text.y > FlxG.height)
         text.y = 0 - 64;
   }
}

This is the meat of our application.  You will notice that GameState inherits from FlxState.  FlxState is a very important concept in HaxeFlixel development.  Essentially you break your game logic up into a number of different states, how exactly you do do this is up to you.  A common division might be  Title Screen State, Game Playing State, High Score State, Game Over State for example.  Another option is to break your game up into screens, so instead have it look something like Splash Screen State, Main Menu State, Game Playing State, Game Credits State, etc.  Or alternatively you could break your game into levels such as Main Menu, Level One, Level Two, etc.  Really it comes down to whatever fits the structure of your application the best.  Just keep in mind that FlxState are the logical units for breaking down gameplay complexity into manageable pieces and if you hate the idea completely, no problems, you can just throw everything together into a single state if you prefer.

At the end of the day though, the FlxState is a pretty simple data structure with two primary tasks.  First, it contains all the “stuff” that makes up that portion of your game.  In this particular example that “stuff” consists of a single FlxText node, but it could contain dozens or thousands of objects.  Just realize when we call the add() method, we are adding to a collection of Objects contained in the FlxState class.  The second important part of FlxState is to provide a number of callback methods that FlxGame can call.  As I said earlier, FlxGame contains our main game loop.  Each pass through this loop however it calls a series of functions on the currently active FlxState, the most important of which are draw() and update().  It is through these two callbacks that your FlxState derived class is modified over time.  Let’s look back at our example and walk through the code.

First in our create() method, we call our parents constructor so we are properly set up and configured.  We then create a new FlxText object, which is a special sprite (aka, something visible on screen) object for displaying text.  In this case we display the string “Hello World” at 32px height in the default font.  Notice we used a call to FlxG to get the width of the screen.  FlxG is a special global helper class containing handy information such as width and height of the screen, the default camera, access to input and more.  You can also get read only access to the FlxGame class we created earlier.  Once we create our FlxText object, we format the text so it’s aligned in the center and drawn in red.  Next we call the add() method, adding the text object to the GameState.  Once added it will automatically be drawn every frame unless disabled.

Next we implement the update() method.  As mentioned earlier, this is a callback function that is going to be called by FlxGame every pass through the game loop.  The one parameter it receives is a Float with the amount of time that elapsed since the last pass through the game loop.  This is extremely handy as it enables us to determine just how fast our game is running.  In this particular case all we do is update the text object’s y coordinate ( we will talk more about coordinates shortly, don’t worry ) scrolling until our text is off screen, at which case we go back to the top and start all over.  Please note that this particular code will run at different speeds depending on how fact the device it runs on is!  We will look at ways to make the code run at the same speed on all machines in a future tutorial.  For now, when you run this code you should see:

Hello

 

In the next tutorial we will dive a bit deeper into drawing graphics on screen.

 

The Video

Programming , , ,

15. March 2017

 

There is no requirement to use Visual Studio Code when developing in Haxe, it is however the editor I will be using for this series.  If you would prefer to use HaxeDevelop, be sure to check this earlier tutorial on how to get up and running.  There are several other editor options available with varying levels of Haxe language support.

 

First things first, we need to install Visual Studio Code, you can download it here.

image

 

The install process is pretty straight forward, run the installer and chose the defaults and you should be fine.  Once installed run Visual Studio Code.

 

Now we need to add Haxe language support.  Click the extensions tab, filter on “haxe” and click the install button for “Haxe -- Haxe language support”.

image

 

Once installed it will prompt you to reload Visual Studio Code.  Do so.

image

 

If you haven’t already, create a project.  Instructions for doing so are available here.  Projects are folder based in Visual Studio Code.  To load your project either switch to the project directory from the commandline and type “code .” or load Visual Studio Code and select File->Open Folder.

image

 

Now you can run your game using Ctrl (Or Cmd) + Shift + P to bring up the command palette.  Now enter run task, like so:

image

 

Next pick the target platform you want to build for:

image

 

And TADA, your running application, assuming everything worked right:

image

 

If an error occurred, it will be show in the Problems panel:

image

 

Granted this process is a bit of a pain in the backside.  Thankfully there is a short cut for building and running the default build.  Simply hit Ctrl + Shift + B and it will compile for the default platform.  So… what is the default platform?  That would be Flash.  This of course means you have to have a Flash player installed.  Thankfully you can download one here.

 

What do you do if you want to change the default platform?  It’s a simple enough task, simply locate the file tasks.json in the .vscode folder.  Next locate the line “isBuildCommand”:true, and make sure this is copied to the entry you want to be the default build.  Like Highlanders, there can be only one, so be sure to erase it from the default “flash debug” task.

image

 

The Video

Programming , ,

13. March 2017

 

Welcome to our tutorial series on creating games using Haxe and HaxeFlixel.  This particular tutorial is going to cover setting up your Haxe development environment, installing and configuring HaxeFlixel and finally creating your first simple game.  Throughout this series I will be using Visual Studio Code as my editor, you can learn more about setting up Visual Studio Code for Haxe development here.

 

First we need to install the Haxe toolchain.  First head on over to the Haxe download page and pick the installer appropriate for your development platform.

image

 

 

 

 

 

 

Run the installer.  The default settings should be fine.

image

 

Now we need to install Haxe Flixel.  With Haxe installed we can now use command line tools to finish the installation process.  Create a new command prompt or terminal as Administrator if possible.  Then run the command

haxelib install flixel

image

This will download all the various required libraries for HaxeFlixel to run including lime ( a low level hardware library ) and OpenFL.  Please note that as of writing, HaxeFlixel is NOT compatible with the most recent version of OpenFL and Lime, hopefully this is fixed soon.  Don’t worry though, the above command will download and configure the correct version.

 

Next run the command

haxelib run lime setup

 

Finally, HaxeFlixel has a set of command line tools and templates available, I will be using these tools for this tutorial series, so lets install those as well.  Run the following two commands:

haxelib install flixel-tools

haxelib run flixel-tools setup

 

image

 

At this point the “flixel” command is now available for you.  Let’s use it to create a new game project.  In the directory you want to create your game, enter:

flixel tpl –n “MyFirstFlixelGame”

 

A new project will be created for you and if you selected an IDE during the install process, it will automatically open:

image

 

As part of the previous process several demos were installed as well.  If you want to jump into some code, instead run the command:

flixel create

This will present you will all of the available templates you can create from:

image

 

That’s it for the setup process, in the next tutorial we jump in to the code of our first application.

 

The Video

Programming , ,

21. February 2017

 

Somewhat delayed from the rest of the Defold Engine tutorial series, I realized there was a major gap in subjects we covered... GUI programming.  Defold actually has some really solid UI functionality built in, and in this tutorial we are going to look at the basics of handling a UI in Defold. Well very conventional in it’s approach, if you’ve gotten accustomed to the Defold way of doing things, you will find Defold’s approach to handling UI remarkably consistent to the way you do just about everything else using the Defold game engine.

 

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

 

In this tutorial we are going to implement the simplest of UI, but all of the concepts of a much more complicated interface can easily be extrapolated from what we cover here. We are going to create a UI that pops up when the user hits the ESC key, dimming the existing screen, showing the UI, handling input, then un-dimming the UI.  There is a ton more UI functionality available in Defold, but it should be fairly easy to pick it up once you’ve got the basics down.  So without further ado, lets jump right in.

 

A UI in Defold consists of two different file types, a .gui and a .gui_script file.  A gui_script file is just a traditional lua script file, but has access to the gui namespace.    Let’s take a step by step look at creating a UI that appears when you hit the ESC key and handles a simple button being clicked.

 

First we need a font, drag any applicable TTF file to your project.  I personally created a folder called MyFont and dragged it there.  Next I created a Font file in the same folder.

image

 

Next open the newly created Font file and select the ttf file you just imported.  Please note that the filter is broken and you should manually type *.ttf to locate your font.

image

After selecting the font I also increased the size to 30pts.  This is aesthetic and purely optional.

 

Now that we have a font selected, we need to define an Input map.  I fully describe the process here for more information on how Input Maps work in Defold.  This are the bindings I created:

image

 

Next we create our gui file.  Simply select Gui File:

image

 

We can use the Gui File to arrange the controls that make up our UI.  Here are the options:

image

 

In this simple UI we are simply going to create a button by creating a box then adding a text label to it.  We will also create a label telling the user to click the button.  First we need to set up our font that we created earlier.  In the GUI editor, right click Fonts and select Add Font:

image

 

When prompted, select the font you just created:

image

 

Now right click Nodes and add a Box.  Once created it can be positioned by hitting W then moving manually.

TransformBox

 

Next right click the newly created box node and create a child Text field:

image

 

Child nodes automatically inherit the position of their parents.  With the Text node selected, lets set it’s font and text, like so:

image

 

I also created another Text field telling the user to click the button.  This one in the root of the GUI hierarchy and not parented to the box.  You’re outline should look something like:

image

 

While your Gui layout should look something like:

image

 

Now that we have a gui file, let’s right a script that will display it.  In our main.collection I simply create a new script and attach it to the default logo objecct.

image

 

Now of course we need to add the UI to our game object.  Create a new root level GameObject named UI, then add component from file and select our gui file:

image

 

So now you main.collection should look something like:

image

Now we enter the following code for main.script:

function init(self)
	-- we want focus and to hide our UI until needed
    msg.post(".", "acquire_input_focus")
    msg.post("UI","disable");
end


function on_message(self, message_id, message, sender)
	-- Wait for a message from the UI layer that the UI has been dismissed
	-- un-dim our sprite
    if(message_id == hash("DONE_UI")) then
    	go.set("#sprite","tint.w",1.0)
    end
end

function on_input(self, action_id, action)
	-- If the user hits the ESC show the UI and dim our sprite
    if(action_id == hash("ESC") and action.released) then
    	-- UI needed now, reenable
    	msg.post("UI","enable")
    	go.set("#sprite","tint.w",0.2)
	end
end

 

This code does a couple things, first on input it tells Defold we want to get input messages.  We also start out by disabling the UI, by sending it the built-in message disable.  When the user actually hits the escape key, we send a message to re-enable the UI layer.  We also dim the logo sprite so it’s not visually in focus when the UI is active.  Also note we wait for the DONE_UI message to undim our sprite.  This is sent by the UI script, which we will create now.

 

If you select your .gui file, in the properties you will notice there is a setting for Script.

image

 

There is a special kind of script, .gui_script, that is used to control gui objects, the Gui Script File.  Let’s create one in the same folder as our .gui file:

image

 

This is a standard lua script, but it has access to the gui namespace.  Once you’ve created your gui_script, set it as the script for your gui file.  Now enter the following script:

function init(self)
	-- We want input control.  AKA, pump input to the UI
    msg.post(".", "acquire_input_focus")
    
end

function on_message(self, message_id, message, sender)
	-- Expect to be enabled by main when needed.  Acquire focus and set text back to click me
	if(message_id == hash("enable")) then 
		msg.post(".", "acquire_input_focus")
		gui.set_text(gui.get_node("text"),"Click Me")
	end
end

function on_input(self, action_id, action)
	-- handle left clicks.  On left click, see if click was within box
	-- if so change our text (this wont actually be seen), disable ourself and pass a message back
	-- to logo that we are done so it can undim itself
	if(action_id == hash("LEFT_CLICK") and action.released == true) then
		local box = gui.get_node("box")
		if(gui.pick_node(box,action.x,action.y)) then
			local text = gui.get_node("text")
			gui.set_text(text,"Clicked")
			msg.post(".","disable")
			msg.post(".","release_input_focus")
			msg.post("/logo",hash("DONE_UI"))
			
		end
	end
end

 

This code waits for the enable message then sets input focus so the gui can receive input messages from Defold.  It also illustrates how you could change the text of a component within the gui.  The most important logic is in the on_input event handler.  We wait for the LEFT_CLICK input.  We then check to see if the click was within our box, if so we set the text of our control ( which is somewhat pointless as it’s about to be hidden! ) to “Clicked”, disable our self, release input focus then send the message DONE_UI back to main.script.  Now if you run the code:

GIF

 

Of course we only scratched the surface of what you can do in a Defold gui, but that should certainly get you started!

 

The Video

Programming , ,

6. February 2017

 

In our previous tutorial we materials in our ongoing Babylon Tutorial Series but today we are going to take things a step higher up and let someone else worry about doing the work for us.  Today we will look at exporting 3D models from Blender for use in our game.  A number of exporters exist (3ds Max, FBX, Cheetah, Unity), but today we are specifically going to talk about using Blender.

First we need to download and install the plugin.  Fortunately they make a zip version available for download.  Head on over to https://github.com/BabylonJS/Babylon.js/blob/master/Exporters/Blender/Blender2Babylon-5.2.zip and click Download:

image

 

Save the zip file somewhere you will remember.  Now fire up Blender.  Select File->User Preferences…  then select the Add-Ons tab

image

 

Now choose Install From File… and select the newly downloaded zip.  Then in the filter area type “Bab” and Import-Export: Babylon.js should be available.  Simply check the checkbox to the right hand side to enable it.  We can now export our scene as a .babylon file for use in our game.  Simply select File->Export->Babylon.js:

image

 

There are no settings for the exporter, so simply pick your game asset directory and click Export Babylon.js Scene.  A .Babylon file and all of your textures will be created in your selected save location:

image

 

Now let’s look at the code required to load and display this model in our game:

    window.addEventListener('DOMContentLoaded', function(){
        var canvas = document.getElementById('canvas');

        var engine = new BABYLON.Engine(canvas, true);
        engine.enableOfflineSupport = false; // Dont require a manifest file
        var createScene = function(){
            var scene = new BABYLON.Scene(engine);
            scene.clearColor = new BABYLON.Color3.White();


            var camera = new BABYLON.ArcRotateCamera("arcCam",
                    BABYLON.Tools.ToRadians(0),
                    BABYLON.Tools.ToRadians(0),
                    10.0,BABYLON.Vector3.Zero(),scene);
            camera.attachControl(canvas,true);
            var light = new BABYLON.PointLight("PointLight",new BABYLON.Vector3(
            0,0,0),scene);
            light.parent = camera;
            light.intensity = 1.5;

            BABYLON.SceneLoader.ImportMesh("","","ShippingContainer.babylon",
            scene,function(newMeshes) {
                newMeshes.forEach(function(mesh){
                    mesh.rotation = new BABYLON.Vector3(BABYLON.Tools.ToRadians(
                    45),0,0);
                }                );
            });

            return scene;
        }

        var scene = createScene();
        engine.runRenderLoop(function(){
            scene.render();
        });

    });

 

The magic is done using the Y() function call.  You can load a specific asset from within the .babylon file by specifying it’s name, but in this case we just want the whole thing.  Import mesh has a callback when the mesh is loaded ( it’s loaded async, so you need to use this callback ) and it’s passed an array of Mesh objects.  We simply loop through this array ( in this example it’s only one item long, so we could have just as easily done newMeshes[0] and accomplished the same thing ).  Sometimes you will need to reposition your objects when loaded due to different coordinate systems, this example shows rotating each mesh by 45 degrees along the X axis.

 

This example uses the ShippingContainer blend file available as part of the Patreon dropbox assets, but you can use any applicable Blend file to create the example.  If you are a Patreon support (thanks by the way!) you can find this model in Art\Blender\ShippingContainer and the code is all available (including the exported Babylon file) in Tutorial Series\Babylon\5 - PartFive – Models.

 

When we run this example, we should see:

GIF

 

The Video

Programming, Art , , , ,

Month List

Popular Comments