Monday, January 21, 2013

The Three Simple Rules of Flocking Behaviors: Alignment, Cohesion, and Separation

In the natural world, organisms exhibit certain behaviors when traveling in groups. This phenomenon, also known as flocking, occurs at both microscopic scales (bacteria) and macroscopic scales (fish). Using computers, these patterns can be simulated by creating simple rules and combining them. This is known as emergent behavior, and can be used in games to simulate chaotic or life-like group movement. 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

In this tutorial, I will cover the three main rules used to simulate flocking and explain how to implement each one.  Before we begin, here’s some terminology I’ll be using:
  • Agent: A single entity or character.
  • Velocity vector: An agent’s current velocity.
  • Neighborhood: A certain area around the agent, used to look for other agents.
  • Resultant: The vector obtained from the calculations of the rule.
This demo shows the effects of the three flocking rules which I’ll explain in this tutorial: alignment, cohesion, and separation.
The full source code for this demo can be downloaded here, so this article will only highlight the most important aspects of the implementation. Feel free to download the source if you wish to learn more.

Alignment

Image adapted from Craig Reynolds’ article
Alignment is a behavior that causes a particular agent to line up with agents close by. First, we’ll make a function that takes an agent and returns a velocity vector.
public function computeAlignment(myAgent:Agent):Point
{
}
We’ll need two variables: one for storing the vector we’ll compute, and another for keeping track of the number of neighbors of the agent.
var v:Point = new Point();
var neighborCount = 0;
[...]
Read more: The Three Simple Rules of Flocking Behaviors: Alignment, Cohesion, and Separation

Tuesday, January 15, 2013

Going Old School: Making Games With a Retro Aesthetic

Everything old is new again, and retro games are more popular than ever. Bolstered by nostalgia and the abundance of casual and arcade-style games on iOS and Android devices, old school games are making a comeback. In this tutorial I’ll give you some tips on creating a successful retro-themed game.

Choosing a Retro Style

What do we mean when we talk about ‘retro’ games? There’s no concrete definition, but I typically think of games made before 1990. This includes games from consoles like the GameBoy, NES, Atari 2600, and Commodore 64, as well as classic arcade games like Pac Man, Centipede, and Space Invaders.
All of those examples use blocky, pixelated, bitmap (or ‘raster’) graphics. These are the type of games that probably come to mind for most people when they think of retro games.
Retro Games with Raster Graphics
Raster Graphics: Pac Man (Arcade), Frogger (Atari 2600), Super Mario Bros. (GameBoy)
But the earliest video games actually used vector graphics. Games like Battlezone, Asteroids and Tempest were rendered with brightly glowing lines instead of blocky pixels.
Retro Games with Vector Graphics
Vector Graphics: Battlezone (Arcade), Tempest (Arcade), MineStorm (Vectrex)
Another type of game us old folks used to play were simple handheld games that used a monochrome LCD display and extremely simple game mechanics.
Retro Games with LCD Graphics
LCD Graphics: Donkey Kong Jr. (Game & Watch), Mario’s Cement Factory (Game & Watch)
In this tutorial, we’re going to talk about the more popular raster graphics games, but I mention these other types of games because they are not often emulated, and I think there is a lot of opportunity for game designers to do something really cool with those styles.

Creating a Color Palette

To create a convincing retro look, you’ll want to work with a limited set of colors.
Old-school game consoles were only able to display a limited number of colors. Depending on the system, graphics would be shown in black and white, grayscale, or 8- or 16-bit color. You can see examples of the exact color palettes from specific systems on Wikipedia, but it’s not important to choose historically accurate colors as long as you maintain a consistent style within your game.
We don’t face the same hardware limitations we did in the past, but keeping your palette limited to a few carefully chosen colors will not only emphasize the retro aesthetic, it will also help to define the identity of your game. Look at these two examples of color palettes from Super Mario Bros.:
Color Palettes from Super Mario Bros.
The colors are so distinct, you can almost recognize the game just from the color swatches.
David Sommers has a nice collection of classic game palettes at ColourLovers.com.
The exact colors you choose will depend on the theme and mood of your game, but if you take the time to choose a good set of colors your game will feel as iconic as the classics. Take a look at these modern examples:
Modern Games with Retro Palettes
Canabalt by Adam Atomic, The Last Rocket by Shaun Inman, Fez by Polytron
If you’re having trouble choosing colors that work well together, check out this great tutorial by Tyler Seitz, Picking a Color Palette for Your Game’s Artwork.

Choosing a Pixel Size

Retro raster games are most easily recognized by their big chunky pixels, from a time when screen resolutions were much lower. In today’s world of HD screens and Retina displays, the physical pixels on our devices are barely visible – not nearly prominent enough to get the retro blocky look.
Scaling Up a Game Sprite
In this example each pixel from our character graphic is being displayed on screen with four physical pixels.
To account for this, we need to use multiple physical pixels to display each visible pixel in our game graphics.
Different Scale Factors
You can decide what level of scaling is appropriate for your game depending on how blocky you want your game to look. Usually scaling up to two or three times normal size gives a good effect. Keep in mind that the bigger you go, the less you’ll be able to fit on the screen.
I recommend that you always let your game engine do your pixel scaling for you. This means that all your assets and text are drawn at 100% (small) and the game simply scales up the entire game canvas to get to the final size. You could actually draw assets with larger pixels, but this will increase file sizes and load times, and can also have a negative impact on game performance.
[...]
Read more: Going Old School: Making Games With a Retro Aesthetic

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 objectgroupCollision” 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