Showing posts with label flashdev. Show all posts
Showing posts with label flashdev. Show all posts

Monday, January 14, 2013

Parsing and Rendering Tiled TMX Format Maps in Your Own Game Engine

In my previous article, we looked at Tiled Map Editor as a tool for making levels for your games. In this tutorial, I’ll take you through the next step: parsing and rendering those maps in your engine. Note: Although this tutorial is written using Flash and AS3, you should be able to use the same techniques and concepts in almost any game development environment.

Requirements


Saving in XML Format

Using the TMX specification we can store the data in a variety of ways. For this tutorial we will be saving our map in the XML format. If you plan on using the TMX file included in the requirements section you can skip to the next section. If you made your own map you will need to tell Tiled to save it as XML. To do this, open your map with Tiled, and select Edit > Preferences… For the “Store tile layer data as:” dropdown box, select XML, as shown in the image below:
Now when you save the map it will be stored in XML format. Feel free to open the TMX file with a text editor to take a peek inside. Here’s a snippet of what you can expect to find:
<map version="1.0" orientation="orthogonal" width="20" height="20" tilewidth="32" tileheight="32">
 <tileset firstgid="1" name="grass-tiles-2-small" tilewidth="32" tileheight="32">
  <image source="grass-tiles-2-small.png" width="384" height="192"/>
 </tileset>
 <tileset firstgid="73" name="tree2-final" tilewidth="32" tileheight="32">
  <image source="tree2-final.png" width="256" height="256"/>
 </tileset>
 <layer name="Background" width="20" height="20">
  <data>
   <tile gid="13"/>
   <tile gid="2"/>
   <tile gid="1"/>
   ...
  </data>
 </layer>
 <layer name="Top" width="20" height="20">
  <data>
   <tile gid="0"/>
   ...
  </data>
 </layer>
 <objectgroup name="Collision" width="20" height="20">
  <object x="287" y="354" width="127" height="60"/>
 </objectgroup>
</map>
As you can see, it simply stores all the map information in this handy XML format. The properties should mostly be straightforward, with the exception of gid – I will go into a more in-depth explanation of this later on in the tutorial. Before we move on, I would like to direct your attention to the objectgroup “Collision” element. As you may recall from the map creation tutorial, we specified the collision area around the tree; this is how it is stored. You can specify power-ups or player spawn point in the same manner, so you can imagine how many possibilities there are for Tiled as a map editor!

Core Outline

Now here’s a brief rundown on how we will be getting our map into the game:
  1. Read in the TMX file.
  2. Parse the TMX file as an XML file.
  3. Load all the tileset images.
  4. Arrange the tileset images into our map layout, layer by layer.
  5. Read map object.

Reading in the TMX File

As far as your program is concerned, this is just an XML file, so the first thing we want to do is read it in. Most languages have an XML library for this; in the case of AS3 I will use the XML class to store the XML information and a URLLoader to read in the TMX file.
xmlLoader=new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, xmlLoadComplete);
xmlLoader.load(new URLRequest("../assets/example.tmx"));
This is a simple file reader for "../assets/example.tmx". It assumes that the TMX file is located in your project directory under the “assets” folder. We just need a function to handle when the file read is complete:
private function xmlLoadComplete(e:Event):void {
   xml = new XML(e.target.data);
   mapWidth = xml.attribute("width");
   mapHeight = xml.attribute("height");
   tileWidth = xml.attribute("tilewidth");
   tileHeight = xml.attribute("tileheight");
   var xmlCounter:uint = 0;

   for each (var tileset:XML in xml.tileset) {
      var imageWidth:uint = xml.tileset.image.attribute("width")[xmlCounter];
      var imageHeight:uint = xml.tileset.image.attribute("height")[xmlCounter];
      var firstGid:uint = xml.tileset.attribute("firstgid")[xmlCounter];
      var tilesetName:String = xml.tileset.attribute("name")[xmlCounter];
      var tilesetTileWidth:uint = xml.tileset.attribute("tilewidth")[xmlCounter];
      var tilesetTileHeight:uint = xml.tileset.attribute("tileheight")[xmlCounter];
      var tilesetImagePath:String = xml.tileset.image.attribute("source")[xmlCounter];
      tileSets.push(new TileSet(firstGid, tilesetName, tilesetTileWidth, tilesetTileHeight, tilesetImagePath, imageWidth, imageHeight));
      xmlCounter++;
   }
   totalTileSets = xmlCounter;
}
This is where the initial parsing is taking place. (There are a few variables we will keep track of outside this function since we will use them later.) Once we have the map data stored, we move onto parsing each tileset. I’ve created a class to store each tileset’s information. We’ll push each of those class instances in an array since we will be using them later:
public class TileSet
{
   public var firstgid:uint;
   public var lastgid:uint;
   public var name:String;
   public var tileWidth:uint;
   public var source:String;
   public var tileHeight:uint;
   public var imageWidth:uint;
   public var imageHeight:uint;
   public var bitmapData:BitmapData;
   public var tileAmountWidth:uint;

   public function TileSet(firstgid, name, tileWidth, tileHeight, source, imageWidth, imageHeight)
   {
      this.firstgid = firstgid;
      this.name = name;
      this.tileWidth = tileWidth;
      this.tileHeight = tileHeight;
      this.source = source;
      this.imageWidth = imageWidth;
      this.imageHeight = imageHeight;
      tileAmountWidth = Math.floor(imageWidth / tileWidth);
      lastgid = tileAmountWidth * Math.floor(imageHeight / tileHeight) + firstgid - 1;
   }
}
Again, you can see that gid appears again, in the firstgid and lastgid variables. Let’s now look at what this is for.

Understanding “gid“

For each tile, we need to somehow associate it with a tileset and a particular location on that tileset. This is the purpose of the gid. Look at the grass-tiles-2-small.png tileset. It contains 72 distinct tiles:
We give each of these tiles a unique gid from 1-72, so that we can refer to any one with a single number. However, the TMX format only specifies the first gid of the tileset, since all of the other gids can be derived from knowing the size of the tileset and the size of each individual tile. Here’s a handy image to help visualize and explain the process.
So if we placed the bottom right tile of this tileset on a map somewhere, we would store the gid 72 at that location on the map. Now, in the example TMX file above, you will notice that tree2-final.png has a firstgid of 73. That’s because we continue counting up on the gids, and we don’t reset it to 1 for each tileset. In summary, a gid is a unique ID given to each tile of each tileset within a TMX file, based on the position of the tile within the tileset, and the number of tilesets referred to in the TMX file.

Loading the Tilesets

Now we want to load all the tileset source images into memory so we can put our map together with them. If you aren’t writing this in AS3, the only thing you need to know is that we’re loading the images for each tileset here:
// load images for tileset
for (var i = 0; i < totalTileSets; i++) {
   var loader = new TileCodeEventLoader();
   loader.contentLoaderInfo.addEventListener(Event.COMPLETE, tilesLoadComplete);
   loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, progressHandler);
   loader.tileSet = tileSets[i];
   loader.load(new URLRequest("../assets/" + tileSets[i].source));
   eventLoaders.push(loader);
}

[...]
Read more: Parsing and Rendering Tiled TMX Format Maps in Your Own Game Engine

Monday, December 17, 2012

Flash Haxe Gaming SDK, their tools, our tools

So Adobe released a few weeks ago its Gaming SDK for flash. The package includes Starling, Away3D and Feathers, three well know quality open source ActionScript3 libraries. You can easily find some externs for most of them on http://lib.haxe.org, which is great! However, during the development of my last game (which used Starling and Haxe) I found out that using haxelibs wasn't enough. A lot of good stuff is happening in the AS3 side, Starling is improving day after day on Github, users create really useful extensions for it. Time is precious and we don't want to write externs for everything or rewrite everything in haxe do we? Thanks to the great haxe/flash support, we can easily use all the good stuff in a matter of seconds, we can hack AS3 code and use the result from Haxe too. In this post I will try to teach beginners how to fish AS3 :)
  • how to compile a bunch of .as files into a .swf using the Flex SDK.
  • how to use those .swf files in haxe (with no extra work)
  • how to patch things when haxe is not happy with the .swf
We'll end up with the entire Adobe Gaming SDK, and more, for Haxe. But the journey is more important than the destination. NOTE: If you are not interested in the process and just want the SDK, I created a bunch of github repositories to host the results. See the test repository to learn how to play with it https://github.com/labe-me/haxe-gaming-sdk-test NOTE: I do not intend to write any extern for these libraries (I am too lazy for that), hence I won't submit them to haxelib. Feel free to use my work in any way you want to create nice haxelib packages. As far as I am concerned I really enjoy the haxelib git support :) Start. We are going to compile .as files, you'll need to install the Flex SDK. Let's learn how it works with Starling. (1) get the library sources:
[...] read more: Flash Haxe Gaming SDK, their tools, our tools

Thursday, December 13, 2012

Creating a Custom Virtual Keyboard

Although AIR for iOS offers access to the iOS virtual keyboard, you have limited control over the type of keyboard that appears. If you want additional keyboard configurations within your Flash project then you’ll need to build your own custom keyboard component. Although this will require some development effort it will allow you to tailor the user experience. For certain apps such as games, you may actually find a custom keyboard is the preferred option, as it will better fit your visual design.
Let’s see how to create one using Flash.
Flash iOS Apps CookbookThis tutorial is a previously unreleased recipe from Flash iOS Apps Cookbook and supplements the content found in Chapter 7, Working with Text and the Virtual Keyboard.
Flash iOS Apps Cookbook provides the recipes required to build native iOS apps using your existing knowledge of the Flash platform. Whether you want to create something new or simply convert an existing Flash project, the relevant steps and techniques are covered, helping you achieve your goal.

Getting Ready

An FLA has been provided as a starting point.
Download this recipe’s accompanying source bundle and open chapter7/recipe8/recipe.fla into Flash Professional.
The visuals for this application have already been created. Sitting on the stage is a virtual keyboard and a dynamic text field. The text field will be used to output what the user types.
The dynamic text field has been named field while the movie clip instance that represents the virtual keyboard has been named keyboard.

Entering a player's name with a custom virtual keyboard.
With the Selection tool (V) selected, double-click on the keyboard instance to examine its timeline. The keyboard contains 28 keys – 26 for the letters of the alphabet, an ok key for when the user is finished typing, and a del key to delete a character. You’ll find that each alphabetic key is represented by its own movie clip and that the instances are named a_key to z_key. This naming convention makes it easy to determine the letter that a key represents by simply examining the first character of its instance name. The remaining two keys have instance names of ok_key and del_key. Additionally there’s a movie clip named surface that sits beneath the keys and represents the keyboard’s body.
Double-click on any one of the keys to examine its timeline. Each is represented by two frames, where the second frame will be shown when the key is being pressed. The movie clip symbol for each key is linked to a class named Button, which was introduced in the Handling user interaction recipe from Chapter 4. Open Button.as and familiarize yourself with the code.

How to do it…

Perform the following steps.
From Flash, select File | New and create a new ActionScript 3.0 class. Name it VirtualKeyboard.
  • Add the following ActionScript to the class:
    [...]
    Read more: Creating a Custom Virtual Keyboard
  • Wednesday, December 12, 2012

    Enable Advanced Telemetry on Flex or old SWFs with SWF Scount Enabler

    Adobe Scout allows developers to profile SWFs like never before. The telemetry data sent by the release Flash Player to Adobe Scout is by default only set to send basic telemetry data. To be able to see data for the AS3 sampler, Stage3D rendering, and DisplayList rendering you have to enable the SWF (password is optional).
    This is done by using the newer asc2 compiler that comes in Flash Builder 4.7 or in the AIR sdk found in the Gaming SDK from Creative Cloud. Currently asc2 only works with ActionScript projects and implements a new flag called -advanced-telemetry or a check box in Flash Builder 4.7 ActionScript project properties.
    To enable SWFs that don’t use asc2, mainly Flex apps or legacy SWFs, you need to use a script to write a specific SWF tag into the SWF file. This doesn’t change the SWF abc code but just adds a SWF tag that Flash Player will use to start sending telemetry data. There is a python script written to help with writing this tag. But the python script requires python and I wanted something a bit easier to use so I created SWF Scout Enabler.

    To use the application all you need to do is drag your SWF into the application and it will create a new SWF (or override if you give it a “” suffix) that is enabled for advanced telemetry.
    The application will also save the last suffix and password used. It also has the ability to re-process the last processed file by clicking on the top right box image.
    Last but not least, the full source of the application can be found on github.
    Download the SWF Scout Enabler AIR application.
    I need to thank Joseph Labrecque for testing out the app.
    Note: This app has been tested on a bunch of SWFs but if it is not working let me know. There seems to be a bug with Adobe Scout on AS2 SWFs older than version 8. Adobe Scout will never do ActionScript sampling on AS2 SWFs but it will do basic telemetry.

    Read more: Enable Advanced Telemetry on Flex or old SWFs with SWF Scount Enabler

    Tuesday, December 11, 2012

    Animating With Asset Sheets: An Alternative to Blitting

    So you’ve got your awesome game in the works, it’s got all sorts of complex physics, epic enemy AI or what-have-you. But it feels lifeless. You want some OOMPH, you want some animation!
    So if you go and look up how to animate, the first answer you come across will most likely be a method using spritesheets and blitting. In fact, almost all tutorials on the web talk about nothing but blitting, as if there’s no other way to animate. But in my experience, there’s a better way to animate your orcs and goblins!
    This method could be called animating with asset-sheets – or more technically, tweening with asset-sheets – as opposed to using sprite-sheets. Before we get into exactly what this means, let’s consider an important question:

    What’s Wrong With Blitting?

    Below are some reasons as to why you would not want to use blitting in certain cases.

    1. It Takes a Lot of Space

    Whether we’re talking about RAM or disk space, sprite sheets can easily clog things up. Especially if you’re trying to make HD graphics. Huge sprite sheets may have to be split into multiple PNGs, taking up precious RAM and skyrocketing your game’s size if you’re not careful.

    2. It’s Not Dynamic

    What happens when you want to speed up an animation? You could skip some frames, but what about slowing down? The animation would look choppy and ugly. Even if you want to only support 60 fps, what if a computer can run the game faster? You could have jaw-droppingly smooth animations at higher frame rates with no extra work, and it would also look good if you chose to change the game’s frame rate at any time.
    And what if you wanted something to happen when the player’s arms reached some place? Or to have him pick up something? You’d need to manually mark his arm throughout the animation, which may be time-consuming as you can’t get any data about where any of his limbs are from a sprite sheet.

    3. It Doesn’t Allow You to Make Transitions

    What happens when the player is running and suddenly jumps? It cuts to the jump animation right away. This looks choppy, and this would happen every time the animation transitions to a new state. You’d have to make a transition for every pair of animations you have, which is not only insanely time consuming, but also has the adverse effect of increasing your RAM usage as discussed earlier.

    The Alternative

    Using asset-sheets not only allows the animations to be dynamic and scale up with any FPS, as well as transitioning smoothly between any two states, but also takes a tiny tiny amount of disk space and RAM compared to blitting!
    This isn’t even very new. Some popular games use it, like the recently popular Closure.  Its only limitation is that it can’t do frame-by-frame (FBF) animation, since it relies on tweening – so if you have complex explosions, you’ll have to use sprite sheets.
    But for a lot of cases, you’ll find you won’t need to, and it’s more than worth the effort to have a system like this for your game, as some games could rely completely on this, shaving off a ton of overhead. It’s also really cool because it’s similar to how you might animate a 3D game!
    So to summarize:
    Gamedev Animation With Asset-Sheets: An Alternative to Blitting

    Let’s Dive Right In

    This is a character and his asset sheet.
    Gamedev Animation With Asset-Sheets: An Alternative to Blitting
    As the name implies, an asset sheet is a PNG with all the limbs/assets of the character or object separated.
    And here is the animation data in JSON (of course, you can use whichever format you prefer to work with):
    //this snippet shows the first three frames of the "Body" animation
    "-name":"Body",
    "Frame": [
    {
     "-x":"0.65",
     "-y":"-64.45",
     "-rotation":"0.000"
    },
    {
     "-x":"2.45",
     "-y":"-64.45",
     "-rotation":"0.279"
    },
     "-x":"3.30",
     "-y":"-64.05",
     "-rotation":"0.707"
    }
    
    Now combining these two together in an awesome engine, you get:
    Gamedev Animation With Asset-Sheets: An Alternative to Blitting
    And unlike a blitted animation, this could speed down or up, or transition very smoothly. So this is what we'll be doing.

    Step 1: Exporting Your Asset Sheet

    The first step is to get your asset-sheet ready. You can do this in any number of ways. The point is to end up with a sheet containing the assets and a data file containing the positions of the assets in the sheet. This is the exact same method as for making a spritesheet, except in lieu of sprites you add separate assets.
    Export your player's limbs and pieces as individual PNGs, then use a program like Texture Packer to group them into a sheet. There are other programs, but I personally prefer Texture Packer because of how versatile and feature-rich it is.
    Tip: Whatever software you use to make your sheets , make sure there is at least 2px of padding between each asset and 1px extrusion. This will prevent some nasty problems in the future.

    Step 2: Exporting Your Animation Data

    [...]
    Read more: Animating With Asset Sheets: An Alternative to Blitting

    Tuesday, November 27, 2012

    Using GDB script files with the FlasCC GDB

    The Flash C++ Compiler (FlasCC) provides a complete BSD-like C/C++ development environment based on GCC that lets you compile your C/C++ code to target the Adobe® Flash® Runtime (Flash Player and AIR®). With FlasCC you can port almost any existing C/C++ code to the web, across browsers. FlasCC includes tools for building, testing, and debugging C/C++ projects, example projects with source code, and documentation. You can get FlasCC today on the http://gaming.adobe.com/technologies/flascc/ page.
    Today I want to share a quick FlasCC debugging tip. The FlasCC based gdb tool is located in the FlasCC download under sdk/usr/bin/gdb (Mac) or sdk/usr/bin/gdb.exe (Win/Cygwin).
    Before trying this out we need a simple C app to debug. Go ahead and create a file called test.c and put the following code inside:
    C:
    #include <stdio.h>
    int main(int argc, char **argv)
    {
        int i = 0;
        printf("Hello World %d Time\n", i++);
        printf("Hello World %d Time\n", i++);
    }
    And the command to compile the debug SWF with FlasCC is:
    CODE:
    sdk/usr/bin/gcc -g test.c -emit-swf -o test.swf
    The FlasCC gdb relies on an environmental variable called FLASCC_GDB_RUNTIME, if you do not set it before running gdb you'll see the following message inside of the gdb prompt:
    CODE:
    (gdb) run
    Starting program: hello.swf
    Please set the FLASCC_GDB_RUNTIME environment variable to the path to a debugger player or browser.
    The FLASCC_GDB_RUNTIME needs to be set to the standalone debug Flash Player or to a browser that has a debug Flash Player. I recommend for the first time that you try using the FlasCC gdb to download a standalone debug Flash Player from here and us it. I downloaded the Mac version and put in a folder called /Code, which means I would run this command in Ternimal before I call gdb:
    CODE:
    export FLASCC_GDB_RUNTIME=/Code/Flash\ Player\ Debugger.app
    Lets take a look at my command line to see how to put this all together:
    CODE:
    renaun$ sdk/usr/bin/gcc -g test.c -emit-swf -o test.swf
    renaun$ export FLASCC_GDB_RUNTIME=/Code/Flash\ Player\ Debugger.app
    renaun$ sdk/usr/bin/gdb test.swf
    GNU gdb (GDB) 7.3
    Copyright (C) 2011 Free Software Foundation, Inc.
    License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
    This is free software: you are free to change and redistribute it.
    There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
    and "show warranty" for details.
    This GDB was configured as "--host=x86_64-apple-darwin10 --target=avm2-elf".
    For bug reporting instructions, please see:
    <http://www.gnu.org/software/gdb/bugs/>...
    (gdb) b main
    No symbol table is loaded.  Use the "file" command.
    Make breakpoint pending on future shared library load? (y or [n]) y
    Breakpoint 1 (main) pending.
    (gdb) run
    Starting program: test.swf
    0xdddddddd in ?? ()
    Breakpoint 1, 0xf0000051 in main (argc=0, argv=0x200ff0) at test.c:5
    5       int i = 0;
    (gdb)
    So I setup export to the debug Flash Player and then ran the gdb against the SWF. But once in side the gdb command prompt I still need to setup a break point. When trying to setup a break point before starting the SWF it will display another warning which needs a yes response. After responding with a yes I can then type run.
    Here is the trick, by using gdb -x script.txt we can run it all in one command. Instead of having to type in my break point each time or responding yes. This is how it works, create a script.txt file and put in the following gdb commands:
    CODE:
    set breakpoint pending on
    b main
    r
    The first line sets the default warning option to be yes so you dont have to worry about it not being set. The second command sets a break point at the main function. And the last command runs the gdb, telling it to start. The command to use the gdb script is below:
    CODE:
    renaun$ sdk/usr/bin/gdb -x script.txt test.swf
    Another handy command to put in script.txt is the set as3namespace com.renaun.test command. This is needed if you create a FlasCC SWC with a custom namespace.

    © %FIRST Erickson - visit the <renaun.com:flexblog text="{ ModelLocator.myThoughts }"/>


    Read more: Using GDB script files with the FlasCC GDB

    Wednesday, October 17, 2012

    Getting all the collection names with MongoDB and AS3

    At work I've been making on a quick tool to modify objects in MongoDB for our upcoming game. As I remembered reading about some AS3 drivers that allow you to directly connect to a Mongo database rather than need to use a server script, I decided to take a look. And immediately hit a roadblock.
    In the main libs I found; @s9tpepper's MongoAS3 lib, and JMCNet's full-mongo-flex-driver; there was no built-in way to get the collections in a database. If you've worked with Mongo before, you'll know that it's slightly important to know that.
    Both libs provided access to the Mongo runCommand() command, but no combination of keys seemed to do the job. Of course, you could always just keep a static Array of Strings, but where's the fun in that?
    Other languages and drivers usually have a function along the lines of getCollectionNames() and with the help of @dun4n's google-fu, we found out how to do it. Mmmm, smells like a hack!

    How it works

    So, for a database that looks like this: [...]
    Read more: Getting all the collection names with MongoDB and AS3

    Tuesday, October 16, 2012

    Create a Simple Asteroids Game Using Component-Based Entities

    In the previous tutorial, we created a bare-bones component-based Entity system. Now we’ll use this system to create a simple Asteroids game.

    Final Result Preview

    Here’s the simple Asteroids game we’ll be creating in this tutorial. It’s written using Flash and AS3, but the general concepts apply to most languages. The full source code is available on GitHub.

    Class Overview

    There are six classes:
    • AsteroidsGame, which extends the base game class and adds the logic specific to our space shoot-’em-up.
    • Ship, which is the thing you control.
    • Asteroid, which is the thing that you shoot at.
    • Bullet, which is the thing that you fire.
    • Gun, which creates those bullets.
    • EnemyShip, which is a wandering alien who’s just there to add a bit of variety to the game.
    Let’s go through these entity types one by one.

    The Ship Class

    We’ll start with the player’s ship: [...]

    Read more: Create a Simple Asteroids Game Using Component-Based Entities

    Monday, October 15, 2012

    Avoiding the Blob Antipattern: A Pragmatic Approach to Entity Composition

    Organising your game code into component-based entities, rather than relying only on class inheritance, is a popular approach in game development. In this tutorial, we’ll look at why you might do this, and set up a simple game engine using this technique.

    Introduction

    In this tutorial I’m going to explore component-based game entities, look at why you might want to use them, and suggest a pragmatic approach to dip your toe in the water.
    As it’s a story about code organisation and architecture, I’ll start by dropping in the usual “get out of jail” disclaimer: this is just one way of doing things, it’s not “the one way” or maybe even the best way, but it might work for you.  Personally, I like to find out about as many approaches as possible and then work out what suits me.

    Final Result Preview

    Throughout this two-part tutorial, we’ll create this Asteroids game. (The full source code is available on GitHub.) In this first part, we’ll focus on the core concepts and general game engine.

    What Problem Are We Solving?

    In a game like Asteroids, we might have a few basic types of on-screen “thing”: bullets, asteroids, player ship and enemy ship. We might want to represent these basic types as four separate classes, each containing all the code we need to draw, animate, move and control that object.
    While this will work, it might be better to follow the Don’t Repeat Yourself (DRY) principle and try to reuse some of the code between each class — after all, the code for moving and drawing a bullet is going to be very similar to, if not exactly the same as, the code to move and draw an asteroid or a ship.
    So we can refactor our rendering and movement functions into a base class that everything extends from. But Ship and EnemyShip also need to be able to shoot. At this point we could add the shoot function to the base class, creating a “Giant Blob” class that can do basically everything, and just make sure asteroids and bullets never call their shoot function.  This base class would soon get very large, swelling in size each time entities need to be able to do new things. This isn’t necessarily wrong, but I find smaller, more specialised classes to be easier to maintain.
    Alternatively, we can go down the root of deep inheritance and have something like EnemyShip extends Ship extends ShootingEntity extends Entity. Again this approach isn’t wrong, and will also work quite well, but as you add more types of Entities, you will find yourself constantly having to readjust the inheritance hierarchy to handle all the possible scenarios, and you can box yourself into a corner where a new type of Entity needs to have the functionality of two different base classes, requiring multiple inheritance (which most programming languages don’t offer).
    I have used the deep hierarchy approach many times myself, but I actually prefer the Giant Blob approach, as at least then all entities have a common interface and new entities can be added more easily (so what if all your trees have A* pathfinding?!)
    There is, however, a third way…

    Composition Over Inheritance

    If we think of the Asteroids problem in terms of things that objects might need to do, we might get a list like this: [...]
    Read more: Avoiding the Blob Antipattern: A Pragmatic Approach to Entity Composition

    Saturday, October 13, 2012

    SWF Versioning

    I am sure some of you guys have been confused in the past about the SWF versioning and which version to use when targeting Flash Player or AIR. Romil in the past posted a little table with the history. I decided to give it a little update that you can then bookmark. We will have this posted as an official reference on livedocs soon, but for now here it is!
    Flash Player versionAdobe AIR versionSWF version
    9.0.115.0NA9
    10.01.510
    10.12.010
    10.22.611
    10.32.712
    113.013
    11.13.114
    11.23.215
    11.33.316
    11.43.417
    11.53.518

    Read more: SWF Versioning

    Tuesday, October 9, 2012

    Create a Glowing, Flowing Lava River Using Bézier Curves and Shaders

    Most of the time, using conventional graphic techniques is the right way to go. Sometimes, though, experimentation and creativity at the fundamental levels of an effect can be beneficial to the style of the game, making it stand out more. In this tutorial I’m going to show you how to create an animated 2D lava river using Bézier curves, custom textured geometry and vertex shaders. Note: Although this tutorial is written using AS3 and Flash, you should be able to use the same techniques and concepts in almost any game development environment.

    Final Result Preview

    Click the Plus sign to open more options: you can adjust the thickness and speed of the river, and drag the control points and position points around. No Flash? Check out the YouTube video instead:
    The actual demo runs at a much higher framerate.

    Setup

    The demo implementation above uses AS3 and Flash with Starling Framework for GPU accelerated rendering and the Feathers library for UI elements. In our initial scene we are going to place a ground image and a foreground rock image. Later we are going to add a river, inserting it between those two layers.

    Geometry

    Rivers are formed by complex natural processes of interaction between a fluid mass and the ground beneath it. It would be impractical to do a physically correct simulation for a game. We just want go get the right visual representation, and to do so we are going to use a simplified model of a river. Modeling the river as a curve is one of the solutions we can use, enabling us to have a good control and achieve a meandering look. I chose to use quadratic Bézier curves to keep things simple. Bézier curves parametric curves often used in computer graphics; in quadratic Bézier curves, the curve passes through two specified points, and its shape is determined by the third point, which is usually called a control point.
    Read more: Create a Glowing, Flowing Lava River Using Bézier Curves and Shaders

    Monday, October 8, 2012

    Use Any Sprite As a Stage3D Texture

    Textures are usually simple bitmaps, but what if you wanted to use something more dynamic? How about a SWF you’ve created in Flash Professional? How about a Sprite or MovieClip you’ve created in code? Today’s article will show you how to do just that. First of all, there’s no magic Flash API that accepts a [...]

    Read more: Use Any Sprite As a Stage3D Texture

    Sunday, October 7, 2012

    Implementing Tetris: Collision Detection

    I’m sure it’s possible to create a Tetris game with a point-and-click gamedev tool, but I could never figure out how. Today, I’m more comfortable thinking at a higher level of abstraction, where the tetromino you see onscreen is only a representation of what’s going on in the underlying game. In this tutorial I’ll show you what I mean, by demonstrating how to handle collision detection in Tetris. Note: Although the code in this tutorial is written using AS3, you should be able to use the same techniques and concepts in almost any game development environment.

    The Grid

    A standard Tetris playing field has 16 rows and 10 columns. We can represent this in a multidimensional array, containing 16 sub-arrays of 10 elements:
    Imagine the image on the left is a screenshot from the game – it’s how the game might look to the player, after a tetromino has landed but before another has been spawned. On the right is an array representation of the game’s current state. Let’s call it landed[], as it refers to all of the blocks that have landed. An element of 0 means that no block occupies that space; 1 means that a block has landed in that space. Now let’s spawn an O-tetromino in the centre at the top of the field:
    tetromino.shape = [[1,1],
                       [1,1]];
    tetromino.topLeft = {row: 0, col:4};
    
    The shape property is another multidimensional array representation of the shape of this tetromino. topLeft gives the position of the top-left block of the tetromino: at the top row, and the fifth column in. We render everything. First, we draw the background – this is easy, it’s just a static grid image. Next, we draw every block from the landed[] array:
    for (var row = 0; row < landed.length; row++) {
        for (var col = 0; col < landed[row].length; col++) {
            if (landed[row][col] != 0) {
                //draw block at position corresponding to row and col
                //remember, row gives y-position, col gives x-position
            }
         }
    }
    
    My block images are 20x20px, so to draw the blocks I could just insert a new block image at (col * 20, row * 20). The details don’t really matter. Next, we draw every block in the current tetromino:
    for (var row = 0; row < tetromino.shape.length; row++) {
        for (var col = 0; col < tetromino.shape[row].length; col++) {
            if (tetromino.shape[row][col] != 0) {
                //draw block at position corresponding to
                //row + topLeft.row, and
                //col + topLeft.col
            }
         }
    }
    
    We can use the same drawing code here, but we need to offset the blocks by topLeft. Here’s the result:
    Implementing Tetris: Collision Detection
    Note that the new O-tetromino doesn’t appear in the landed[] array – that’s because, well, it hasn’t landed yet.

    Falling

    [...]

    Read more: Implementing Tetris: Collision Detection

    Saturday, October 6, 2012

    Drawing API with Starling

    Drawing APIThis week a very cool contribution was added to Starling by Robert Silverton, the Graphics API Extension! So what is it? From github: This extension adds Jon Pace's 'Fill' and 'Stroke' display objects, with support for adding arbitrary vertices that are then triangulated for rendering on the GPU. The aim is to reproduce Flash's graphics API as closely as possible via simplified lineTo, moveTo etc calls within Shape.graphics and Sprite.graphics. Once the basics have been reproduced, the API can be augmented with more powerful features. An ear-clipping algorithm is currently used for triangulating the simple polygons generated by the moveTo, lineTo methods. Supports both simple and non-simple (self-intersecting) polygons. For those of you who always felt that not having a drawing API was limiting, there you go. We are already thinking about some new APIs we could add to Flash Player and AIR to make this extension even more powerful. Graphics query, anyone? ;) Feel free to contribute and enhance it. Lee Thomason from our team has already sent some optimizations for curveTo. See you there! [...]

    Read more: Drawing API with Starling

    Tuesday, August 28, 2012

    Using the Composite Design Pattern for an RPG Attributes System

    Intelligence, Willpower, Charisma, Wisdom: besides being important qualities you should have as a game developer, these are also common attributes used in RPGs. Calculating the values of such attributes — applying timed bonuses and taking into account the effect of equipped items — can be tricky. In this tutorial, I’ll show you how to use a slightly modified Composite Pattern to handle this, on the fly.

    Note: Although this tutorial is written using Flash and AS3, you should be able to use the same techniques and concepts in almost any game development environment.

    Introduction

    Attributes systems are very commonly used in RPGs to quantify characters’ strengths, weaknesses, and abilities. If you’re not familiar with them, skim the Wikipedia page for a decent overview.
    To make them more dynamic and interesting, developers often improve these systems by adding skills, items and other things that affect the attributes. If you want to do this, you’ll need a good system that can calculate the final attributes (taking into consideration every other effect) and handle the addition or removal of different types of bonuses.
    In this tutorial, we will explore a solution for this problem by using a slightly modified version of the Composite design pattern. Our solution will be able to handle bonuses, and will work on any set of attributes you define.

    What Is the Composite Pattern?

    This section is an overview of the Composite design pattern. If you are already familiar with it, you might want to skip to Modeling Our Problem.
    The Composite Pattern is a design pattern (a well-known, reusable, general design template) for subdividing something big into smaller objects, in order to create a bigger group by handling only the small objects. It makes it easy to break big chunks of information into smaller, more easily treatable, chunks. Essentially, it’s a template for using a group of a particular object as though it was a single object itself.
    We’re going to use a widely used example to illustrate this: think of a simple drawing application. You want it to let you draw triangles, squares and circles, and treat them differently. But you also want it to be able to handle groups of drawings. How can we easily do that?
    The Composite Pattern is the perfect candidate for this job. By treating a “group of drawings” as a drawing itself, one could easily add any drawing inside this group, and the group as a whole would still be seen as a single drawing.
    In terms of programming, we would have one base class, Drawing, which has the default behaviors of a drawing (you can move it around, change layers, rotate it, and so on), and four subclasses, Triangle, Square, Circle and Group.
    In this case, the first three classes will have a simple behavior, requiring only the user input of the basic attributes of each shape. The Group class, however, will have methods for adding and removing shapes, as well as doing an operation on all of them (for example, changing the color of all shapes in a group at once). All four subclasses would still be treated as a Drawing, so you don’t have to worry about adding specific code for when you want to operate on a group.
    To take this into a better representation, we can view each drawing as a node in a tree. Every node is a leaf, except for Group nodes, which can have children — which are in turn drawings inside that group.

    A Visual Representation of the Pattern

    Sticking with the drawing app example, this is a visual representation of the “drawing application” we thought about. Note that there are three drawings in the image: a triangle, a square and a group consisting of a circle and a square:
    Using the Composite Design Pattern for an RPG Attributes System
    And this is the tree representation of the current scene (the root is the drawing application’s stage):
    Using the Composite Design Pattern for an RPG Attributes System
    What if we wanted to add another drawing, which is a group of a triangle and a circle, inside the group we currently have? We would just add it as we would add any drawing inside a group. This is what the visual representation would look like:
    Using the Composite Design Pattern for an RPG Attributes System
    And this is what the tree would become:
    Using the Composite Design Pattern for an RPG Attributes System
    Now, imagine that we’re going to build a solution to the attributes problem we have. Obviously, we’re not going to have a direct visual representation (we can only see the end result, which is the calculated attribute given the raw values and the bonuses), so we’ll start thinking in the Composite Pattern with the tree representation.

    Modeling Our Problem

    In order to make it possible to model our attributes in a tree, we need to break each attribute into the smallest parts we can.
    We know we have bonuses, which can either add a raw value to the attribute, or increase it by a percentage. There are bonuses which add to the attribute, and others that are calculated after all those first bonuses are applied (bonuses from skills, for example).
    So, we can have:
    • Raw bonuses (added to the raw value of the attribute)
    • Final bonuses (added to the attribute after everything else has been calculated)
    You may have noticed that we are not separating bonuses that add a value to the attribute from bonuses that increase the attribute by a percentage. That’s because we are modeling each bonus to be able to change either at the same time. This means we could have a bonus that adds 5 to the value and increases the attribute by 10%. This will all be handled in the code.
    These two kind of bonuses are only the leaves of our tree. They are pretty much like the Triangle, Square and Circle classes in our example from before.
    We still haven’t created an entity that will serve as a group. These entities will be the attributes themselves! The Group class in our example will be simply the attribute itself. So we will have an Attribute class that will behave like any attribute.
    This is how an attribute tree could look:
    Using the Composite Design Pattern for an RPG Attributes System
    Now that everything is decided, shall we start our code?

    Creating the Base Classes

    We will be using ActionScript 3.0 as the language for the code in this tutorial, but don’t worry! The code will be fully commented on afterwards, and everything that is unique to the language (and the Flash platform) will be explained and alternatives will be provided — so if you are familiar with any OOP language, you will be able to follow this tutorial without problems.
    The first class we need to create is the base class for any attribute and bonuses. The file will be called BaseAttribute.as, and creating it is very simple. Here is the code, with comments afterwards: [...]
    Read more: Using the Composite Design Pattern for an RPG Attributes System

    Thursday, July 12, 2012

    New tutorial: Profiling memory with TheMiner

    Tutorial: Using the Memory profiler

    Most of the time, Flash performance issues come from bad memory management.
    Object instantiation take a lot of time, and since FlashPlayer work with a Garbage Collector, having tons of objects can make it go nuts.
    Good practice is to remove all instantiation from loops, keep a minimum of object in memory and use serialization and bytearrays to keep some data.
    This profiler show you what the VM is reporting as object being allocated and removed (garbage collected).
    Here is what the profiler look like:

    1. Search filter
    Since there is a lot of different object type being managed by the VM,
    just listing them would make it hard to find specific data.
    This input box let you enter any text to filter the visible object using their QName
    When the filter search is ON (there is text inside the box), the box appear green,
    and only class name with the text in it appear in the list [...]
    Read more: New tutorial: Profiling memory with TheMiner

    SWF rebuilding with as3swf code library

    Hey!
    It’s been too long since we’ve had a good
    bandit raid
    topical content here. I’m going to fix it!)
    Today we’ll speak about SWF changing using as3swf code library, as you could already guess from this post topic.
    Let me introduce this library first.
    It was designed to parse, modify, and create SWF files on the fly. You could get all the tags and SWF properties (frameRate, version, etc.) after ByteArray with target SWF parsing. The good thing is that with as3swf you’re free to modify any SWF tags and properties and it is able to save all changes you did! It could even allow you to create a new SWF file from scratch.
    as3swf is available for your experiments at github: https://github.com/claus/as3swf
    Library is pretty alive and have a good communicative author (Claus Wahlers), so feel free to make Pull requests ;)
    BTW, he applied my LZMA compression (more on LZMA – here) support pull request yesterday.
    You should wait for the Flash Player 11.4 release to try as3swf with LZMA-compressed SWFs though.
    One thing as3swf could not provide is a DoABC Tag ABC parsing.
    Author started so library project some time ago, but abandoned it, thus it is no longer supported or actual.
    I should agree with Claus though since a great ABC parsing and creating on the fly library as3commons bytecode already exists and have updates periodically: http://as3-commons.googlecode.com/svn/trunk/as3-commons-bytecode/changelog.txt
    I’ve used it some time ago and was really happy with it. But this is another case…
    I’ll shed a bit of light on my as3swf using purposes: I had a task to replace one SWF tag with completely new data, it was the DefineBinaryData tag to be clearer.
    This is how looks SWF parsing code: [...]
    Read more: SWF rebuilding with as3swf code library

    Citrus Engine on Nape and physics performance improvement

    Hi folks! Since my studies are over and my new portfolio online, I have time to focus on personal projects. Yep, it was time to contribute again to the Citrus Engine. I’ve worked 3 days at full time focusing on its big issue : mobile performances. I’m glad to say that now they are just an old memories!
    6 months ago, I’ve made the CE compatible with Stage3D thanks to Starling and added some cool stuff. CitrusEngineV3 BETA 1 has been downloaded 3047 in 6 months, that’s not bad! However it didn’t see lots of Stage3D game, because it was missing the point : people wants to make mobile games.
    You will find all the sources at the end.
    Nape
    Nape is Luca Deltodesco‘s open-source physics engine written in haXe with the help of his preprocessor caXe. It is written with AVM2 in mind for performance, and utilising another part of his build chain provides a seamless API between AS3 and haXe though it does compile with hxcpp with other targets unknown. The idea behind Nape is to provide a high-performance, powerful and moreover friendly and safe physics engine.
    Nape is faster than Box2D, and easier to handle. Adding it in the CE wasn’t hard, and we use it the same way than Box2D. Using Box2D (Alchemy version) & Stage3D with Starling in the CE you must take a look on Adobe Flash Player Premium announcement if you are targetting Browser games. With Nape, you are no more related to the “premium features license” from Adobe.
    Nape is ready to be use (no bug spotted!), however since I’m really new to Nape, there are some strange behavior whith NapePhysicsObject in the CE (you can see it in this demo). It’s not a problem for a performance test.
    A NapeStarlingGameState Class exemple :
    [...] Read more: Citrus Engine on Nape and physics performance improvement

    Wednesday, June 27, 2012

    Creating “Flux”: A Simple Flash Game With a Gravity Mechanic

    In this tutorial, I’ll explain the major steps and workflow for creating a simple space survival game, based on the gravity mechanic explained in a previous tutorial. This game is written in AS3 using FlashDevelop.

    Play the Game

    Use the left and right arrow keys to manoeuvre your ship, the up and down arrow keys to increase or reduce the size of the magnetic field it produces, and the space bar to reverse the polarity. Collect the white crystals to increase your fuel supply – but avoid the red ones, because they use it up. Don’t hit a rock, or it’s game over!
    In this tutorial, we won’t actually create the full game displayed above; we’ll just get started on it, by making a very simple version with primitive graphics and just one type of object. However, by the end, you should have learned enough to be able to add the other features yourself!
    The game itself is very simple in its current state – take a look at this critique for tips on how you can take it from a simple demo to a full game!

    Let’s Get Started!

    Set up a new AS3 project in FlashDevelop, and set its dimensions to 550x600px.
    package
    {
     [SWF(width = "550", height = "600")]
    
     public class Main extends Sprite
     {
    
     }
    }
    

    Step 1: Identifying the Game Objects

    There are six objects in particle that you can identify from playing the game above:
    • Energy supply – represented by an white oval shape object
    • Asteroid – represented by a rock-like object
    • Energy consumer – represented by a red star bounded with green light.
    • Stars – the background
    • Range indicator – represented by a white circle
    • Ship – player object
    Of course you can add in any other object to make the game more interactive or add a new feature. For this tutorial we’ll just make

    Step 2: The Energy Class

    From the objects we identified, four of them actually work in exactly the same way: by falling from top to bottom.
    They are:
    • Stars
    • Energy supply
    • Energy consumer
    • Asteroid
    In this tutorial, we’re only going to make the “energy supply” objects, out of the four above. So let’s begin by creating these objects and making them fall down, with a random spawning position and speed.
    Start by creating an Energy class:
    package
     {
      import flash.display.MovieClip;
      import flash.events.Event;
    
      public class Energy extends MovieClip
      {
       private var rSpeed:Number = 0;
    
       public function Energy(speed:Number)
       {
        graphics.beginFill(0x321312);
        graphics.drawCircle(0, 0 , 8);
    
        rSpeed = speed;
       }
    
       // we will call this every frame
       public function move():void
       {
        this.y += rSpeed;
        //rotation speed is linked to moving speed
        this.rotation += rSpeed / 8;
       }
      }
     }
    

    Step 3: The GameScreen Class

    This class will eventually control most of the aspects of our game, including the player movement and the game loop.
    Create the class:
    package
    {
    
     public class GameScreen extends MovieClip
     {
    
      public function GameScreen()
      {
    
      }
     }
    }
    
    That’s all we need for now.

    Step 4: Update The Main Class

    We’ll now create an instance of GameScreen within Main:
    Read more: Creating “Flux”: A Simple Flash Game With a Gravity Mechanic

    Saturday, June 16, 2012

    The Math and ActionScript of Curves: Roots

    In the first tutorial of this series, we took a look at drawing curves using equations and AS3. Now, we’re going to tackle solving those equations to find the roots of a curve – that is, the places where the curve crosses a given straight line. We can use this to predict collisions with curved surfaces, and to avoid “tunnelling” in Flash games.

    Step 1: Quadratic Roots

    First, time for some quick math revision. In this tutorial, we’ll just accept and apply the methods we’ll use, but interested readers can refer to Wikipedia’s page on quadratic equations for information about the mathematical deriviations.
    So \(f(x)\) is a quadratic function. If (f(x)) is equivalent to 0, (x) can be obtained by this formula:
    [Given f(x) = ax^2+bx+c, ] [f(x) = 0, x = frac{-b pm sqrt{b^2 - 4ac}}{2a} ]
    (b^2 – 4ac\) is called the discriminant of the formula. If the discriminant is negative, the square root of the discriminant will produce imaginary roots, which we can’t plot. Conversely, if the discriminat is positive, you will have real number roots and you’ll be able to plot them onto the screen.

    Step 2: Visualising Quadratic Roots

    So what are roots? Well in our context they are nothing more than intersection points between the quadratic curve and a line. For example, suppose we are interested to find the intersection point(s) of the following set of equations:
    (
    f(x) = ax^2+bx+c
    g(x) = 0
    )
    This is a typical scenario of looking for the intersection point(s) between a quadratic curve and the x-axis (because the x-axis is the line where y==0). Since by definition the intersection point(s) are shared by (f(x)) and (g(x)), we can conclude that (f(x) = g(x)) for the values of x that we are looking for.
    Read more: The Math and ActionScript of Curves: Roots