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 , , ,

16. March 2017

 

Corona Labs, the makers of the Corona SDK Lua powered game engine, have been sold to Appodeal, a mobile advertising firm.  Back in November of 2015 Corona was acquired by Perk then in September of 2016 it was sold back to the CEO, so it’s been a rocky couple of years over at Corona Labs.  Let’s hope this deal provides some stability for the Corona engine.

 

Details from the announcement:

One of the laurels of Corona SDK is how easy it makes it to build games across platforms without compromising on power and flexibility. For those who need to extend beyond what Corona provides “out of the box” with its many APIs and plugins, the Enterprise version of Corona is perfect.

Appodeal is the functional counterpart to Corona — developers can simply sign up for Appodeal, integrate it with a few lines of code, and connect to multiple demand sources (including AdMob and Facebook Audience Network!). Even though Appodeal connects to dozens of ad networks, developers get the convenience of just one easy payment (with the exception of AdMob and Facebook Audience Network). For developers who want even more power and control over their ad network relationships, Appodeal puts you in the driver’s seat so you can tune as you see fit.

An important note is that the acquisition of Corona Labs by Appodeal does not mean that developers must use Appodeal to monetize their games — Corona Labs will continue to offer and support third-party ad networks into the future, although the integration with Appodeal may get deeper over time with the aim to make it even easier to add monetization to your games.

In addition to a natural fit around building easily and monetizing easily, there’s a shared appreciation around the role Corona plays in the indie developer ecosystem. While many ad networks tend to court developers that already have large audiences, Appodeal recognizes that it’s the smaller developers who make up the vast majority of the ecosystem and that nurturing the relationship with these developers will only promote the possibilities of growth and success.

Appodeal is a global company with offices in San Francisco, Barcelona, and Moscow to name a few. Corona has a large developer community in every nook of the world and Appodeal’s international presence and commitment to serving developers worldwide means higher eCPMs no matter where your users are — and where they can’t deliver, their connectivity to AdMob and Facebook Audience Network solves the problem well.

GameDev News

16. March 2017

 

Wave Engine 2.3.1 was just released.  Wave Engine is a C# powered cross platform 3D game engine I previously featured in the Closer Look series.  The Wave Engine 2.3.1 released brings several new features and improvements, including:

    • OpenGL support on Windows platforms
    • Binary serialization with Protobuf-NET libraryDarkWaveEngine
    • WPF, Windows Form and GTK# templates
    • New Dark and Light themes
    • EdgeCollider2D component added to Physics2D
    • Texture support in vertex shaders
    • New RequiredService attribute
    • Oculus Touch support
    • Relative path support for entity paths
    • Bokeh lens image effect and a new sample illustrating it
    • Add Child button added
    • New QuickStarter sample, with code available on Github.

 

You can learn more about the release here, while Wave Engine can be downloaded here.

GameDev News

15. March 2017

 

Two key Haxe libraries same new releases today, OpenFL 4.9.0 and Lime 4.0.  Lime is a low level cross platform multimedia library, while OpenFL is a reimplementation of several Flash APIs used for game development.  OpenFL is layered over top of Lime, while several other Haxe libraries are in turn dependent on OpenFL.  The OpenFL team also released a blog post describing how to make use of the improved OpenGL bindings in Lime.

 

Details from the release notes.

 

OpenFL 4.9.0 Changelog

  • Updated for Lime 4
  • Added initial support for openfl process for SWF-based assets
  • Added support for loading generated SWFLite bundles in Loader
  • Added support for multiple HTML5 embeds on the same page
  • Added support for loaderInfo.parameters through the HTML5 embed
  • Added support for TextField restrict and maxChars
  • Added support for Float-based keys in Dictionary
  • Added a hack to add stroke support for TextField
  • Improved support for Lime asset manifests in SWF library
  • Improved template behavior to work if Lime is included before OpenFL
  • Improved the behavior of TextField setTextFormat/replaceText
  • Improved support for String-based messages in HTML5 Socket
  • Improved support for non-smoothed bitmapData in SWF libraries
  • Improved "missing font" warning to only occur once per font name
  • Improved "asset not found" warnings to throw errors
  • Improved animated mask support in MovieClip
  • Fixed support for embedded SWF libraries on Flash
  • Fixed the array count calculation in AGAL to GLSL conversion
  • Fixed support for CubeTexture in Stage3D renderToTexture
  • Fixed the reset position after using byteArray.uncompress
  • Fixed a type-cast error when retrieving a missing MovieClip asset
  • Fixed a possible bug when rendering an object with no parent
  • Fixed wrongful error on Stage3D viewport on OS X
  • Fixed cases where stage3D x/y is set before a backbuffer is created
  • Fixed support for GL context loss

 

Lime 4.0.0 Changelog

  • Added support for WebGL 2 APIs on HTML5
  • Recreated GL bindings in preparation for GLES3 support
  • Added support for running different Lime tools to match project version
  • Added WebGL, WebGL 2, GLES 2 and GLES 3 abstracts
  • Added initial support for WebGL/GLES2 extension constants
  • Added GL context, type and version properties
  • Added window.displayMode for full-screen display mode switching
  • Added lime.utils.DataPointer for managing native pointers
  • Added lime.utils.BytePointer for Bytes + offset without a new typed array
  • Added lime.utils.ObjectPool as a convenience API for object pooling
  • Added support for <assets path="" library="" /> for library packing
  • Added support for loading *.bundle directories as asset libraries
  • Added support for ${meta.title} and other project data in project.xml
  • Added support for Cairo textPath
  • Added support for multiple Lime embeds, rewrote HTML5 embed code
  • Added asset type to verbose Preloader messages
  • Added -Dwebgl1 to use a WebGL 1 context instead of WebGL 2 on HTML5
  • Removed deprecated behaviors from Lime 3
  • Updated Gamepad mappings to support additional models
  • Updated HTML5 window to dispatch resize event if parent element is resized
  • Improved support for deferred loading of asset libraries
  • Improved Asset error events, updated to throw errors when assets not found
  • Improved handling of GL context loss on WebGL
  • Improved behavior of asset manifests included as assets of another library
  • Improved behavior of path groups for audioBuffer assets
  • Improved error message if ANDROID_SDK or ANDROID_NDK_ROOT is not defined
  • Fixed caching for HTML5 cache groups
  • Fixed native HTTPRequest if file is not found or uses ~/ for home directory
  • Fixed copying of files when a directory exists of the same name
  • Fixed dispatch of Renderer.onRender when there is no context
  • Fixed dispatch of Renderer.onContextLost on native platforms
  • Fixed use of image.threshold when source is canvas or HTML5 image
  • Fixed missing warning if <icon path="" /> is null
  • Fixed <app path="" /> to be relative to include.xml path
  • Fixed <splashScreen path="" /> to be relative to include.xml path
  • Fixed case where assets could be processed as templates
  • Fixed support for ATF textures on Flash target
  • Fixed ID value for Joystick/Gamepad guid property
  • Fixed double dispatch of preloader complete verbose message
  • Fixed path of -options parameter when calling HXCPP

GameDev News

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 , ,

Month List

Popular Comments