Posts

Showing posts with the label open source

Windows Phone 7 for Flash Developers, Part 2 - BunnyMark benchmark in XNA



To get an idea of what’s possible in terms of 2D games on Windows Phone 7, I have ported my BunnyMark benchmark from AS3/Flash to C#/XNA. The results were very decent for a small device. I could render 3500 bunnies without any slowdown, which is equivalent to what I could do with Bitmaps in Flash on my dual core PC laptop, and about 10 times as many bunnies as Flash on Android could handle. The reason for this great performance, of course is that XNA is hardware accelerated while Flash is not... until next year at least. Here is the source code - watch the video below to see it in action (shot on non-HD camera, so not great quality I'm afraid).



XNA splits game updates (equivalent to ENTER_FRAME event in Flash) into 2 separate functions which you override. There is “Update” (confusingly, functions in C# start with capital letters) where you put all the update logic for your game, and there is “Draw”, where you put all the rendering logic. Like copyPixels blitting in AS3, nothing is drawn to the stage automatically; you must manually call spriteBatch.Draw for each of your game entities.

Ok, now for the slightly weird caveat that I found with the frame rate. XNA by default uses a “fix your timestep” style approach to updates and rendering, where “Update” is called at as close to your target framerate as possible, while calls to “Draw” are dropped if performance is a problem. So when I put my frame rate counter in Update it always shows 30fps, even if actual stage updates are slowing to a jerky crawl. Moving my fps counter to Draw, I expected to see 30fps with a few bunnies, slowing as I add more waves of bunnies. However, what I found was that Draw is never called more than 15 times per second in my tests. So even though the update logic runs at 30fps, the game only really renders at 15fps. Is this something to do with limitations of a mobile device, or just something I don't fully understand? I don’t know. It doesn’t visually look noticeable, although perhaps the movement has a slightly blurry look to it on my device. At 10000 bunnies Draw slowed to about 4fps while update happily skipped along at 30fps.

My overall impressions of the platform from creating the demo are that this is definitely something a reasonably experienced Flash developer can easily turn their hand to. C# and AS3 have only superficial syntax differences, the core of the 2 languages are essentially very similar. The biggest difference comes when you move beyond the standard programming constructs and start requiring utilities like “getTimer”. At these times, Google and StackOverflow.com are definitely your friends – I didn’t get stuck on anything for more than about 5 minutes.
Just to give some examples, here’s a quick comparison of some terms and equivalent features:

Flash >> XNA
AS3 >> C#
int >> int
Number >> float (or double)
Vector.<Bunny> >> Bunny[] or List<Bunny> depending on what features you need.
Math.random() >>random = new Random(); random.NextDouble();
TextField >> SpriteFont
Point >> Vector2
bitmapData.copyPixels or bitmapData.draw >> spriteBatch.Draw
And when casting types the brackets go around the type for some reason:
Number(value) >> (float) value

Other things to look out for are that XNA API methods have “multiple overloads” rather than the optional parameters in AS3. Once you get comfortable with all these things, you stop noticing them and you just get on with it. Here is the source code to the demo – it’s very simple. Next I’m going to port the more advanced BunnyLandMark with a scrolling level and depth sorting. Bai!


Display list vs. blitting - the results!



To get some actual evidence for my opinions on the joys of the Flash display list, I created two demos that I'm calling "BunnyMark", a test of rendering small bouncing bunny pngs with alpha transparency. Since first posting, lots of readers helped by testing on different browsers and operating systems, and I have updated this post with their results.

The results were quite interesting, and not quite what I expected. Blitting was really fast, although actually a little bit slower than I expected, but gave a consistent rendering speed across all platforms. Bitmaps were also pretty fast, although in Safari on Mac performed really badly. I emailed Tinic from the Flash player team about this issue, and he has said he will look into it. Ok so here are the results:
  • The display list demo could render 4000 bunnies at 30 fps on my PC without slowing down. This was replicated by readers on all Mac and Windows browsers except for Mac Safari, where it was down to 10-20 fps. Based on this interesting blog post from Tinic Uro (suggested by Richard Leggett), this seems like it may be something to do with the recent adoption of the Core Animation APIs in Safari. The demos has a lot more layers stacked up than you would need for most games, so this performance drop is unlikely to affect a real game - although I will be following up with a new benchmark to test that hypothesis. Bitmaps faired very badly on Android - it couldn't even render 10 bunnies at 30fps.
  • The blitting demo could render 6000 bunnies at 30 fps without slowing down on my PC, and people with faster machines have reported up to 11000 bunnies at 30 fps. Blitting was also much more effective on Android, where it got up to 600 bunnies at 30 fps, certainly enough performance for an arcade-style game. (Thanks to Philippe Elsass for the Android tests).
So in this example, blitting is about twice as fast. But as I hope you can see, realistically 3000 bunnies is still a lot more than you are going to need in most situations. You can download the source code and see if you can improve the performance of either demo. A couple of readers have recommended performance optimisations, for example suggesting I use a fixed-length vector and using lock() and unlock() on my bitmapData, but neither strategy noticeably improved performance on my machine.

I also wondered whether switching the wmode in the HTML can fix the Safari issues - it doesn't. If you want to try them: Opaque, Transparent, Direct, GPU (both Direct and GPU give 5 fps in Chrome on Windows!). This post from way back in 2008 may possibly shed some light on this topic:
"Just because the Flash Player is using the video card for rendering does not mean it will be faster. In the majority of cases your content will become slower." - Tinic Uro
Just a final note - I ran a similar test to this 2 years ago in Microsoft XNA and was able to get something like 50,000 bunnies going at HD resolution, and 60 fps. I think molehill is going to make this discussion somewhat irrelevant next year - GPU blitting will annihilate both of these approaches. The question will then be, can the display list also be speeded up by the GPU, or is it just too wacky and different to what graphics cards are designed to handle?

A code review of PewPew by Mike Chambers


A very rare event has occurred - the chance to look at, discuss and play with the full source for a Flash game! I've worked with the source to dozens of games by different developers, but I'm normally under a non-disclosure agreement so I cannot divulge the full horrors of what I found there. But Mike Chambers from Adobe has kindly released the full source to his game under MIT open source license, and I thought this could be a great spring-board to open up discussion on the architecture and best practice of making Flash games.

but you also need to download is framework from here: http://github.com/mikechambers/Simple-Game-Framework/archives/master

Mike, hasn't made a game since Flash 4, so if you read this Mike, please take it in the scholarly spirit in which it is intended :)

and to everyone else, remember I am just one guy with some strong opinions, weakly held.

Ok here's my thoughts...

Repository - Mike has not included his framework in the game repository. I'd consider this a bad idea for 2 reasons.
  • A developer coming to the project cold cannot compile it. I believe that the repo of a project should contain everything you need to get started.
  • There is a strong chance that API changes could be made to the framework code that break the build of the game. You really want to use a stable version of a framework rather than having to fix errors every time an update is made to the framework. Then if you want to update to the latest version of the framework you grab the new version and fix all the problems at once. You don't want to come back to make a quick change to your game in 6 months, only to find that you can longer compile because you have changed the API of your framework.
Compiling
  • Mike has chosen to compile from the Flash IDE, which is fine with me and most design-driven agencies. Some developers won't like it, but who cares.
  • Mike has unticked the "include hidden layers" option in the Flash publish settings tab. This is one of my absolute no-nos as it means you can break the build just by hiding and unhiding layers while you're looking around the timeline. If I hadn't encountered this lunacy before, I might have spent hours figuring out why it suddenly wasn't compiling. In the end I had to revert to the original version because I couldn't remember exactly what should and shouldn't be hidden. This is what guides are for, people.
  • One mistake Mike's made that I see quite a lot is that he hasn't put his Main.as document class file in his package structure, it's just in the root of src with the fla. The Main class is just as much a part of the project as anything else, and should be in the package with it's friends.
Game Design
  • the game is a pretty basic asteroid-type shoot 'em up.
  • the home-made visual and audio style is acceptable in the Flash game world, although Mike could have chosen a more hand-written looking font, rather than Helvetica. There are lots of free handwriting fonts out there, and there's always Comic Sans!
  • the controls are optimised for a touchscreen mobile device, with a little virtual joystick in the bottom corner, so it doesn't control well on the desktop.
  • the joystick doesn't allow you to set speed, only direction. A simulated analogue stick would have been nicer.
  • There is some commented-out code for making the ship follow the mouse for browser play, but it is incomplete. Mike would have done better to have a boolean for isMouseControlled which could be switched when targeting the browser, rather than completely commenting out the code. I rarely delete or comment out working code, I'm much more likely to keep it in my class as a switched-off option.
  • At 480x800 it's too tall for a browser game, as you have to consider users with a minimum 1024x768 display.
  • The movement of the ship is not very graceful - it doesn't seem to accelerate or decelerate.
  • The speed of the bullets is way too slow.
  • The collision detection between the bullets and enemies is inconsistent, and bullets often sail under the wings of the UFOs without scoring a hit.
  • There are no roll-overs or even finger cursors on any buttons - again this is probably an artefact of originally being a touch-screen game.
  • There aren't any transitions between screens.
  • The enemies bounce around the screen like asteroids, but they are UFOs, which doesn't make any sense, as you would expect UFOs to know you are there and either attack or make defensive manoeuvres.
Library
  • Mike's library is beautifully arranged into folders with all the items named properly, and no Symbol 1's lying around. I rarely organise my libraries into folders any more - I just rely on the invaluable CS4/5 library search box.
  • Mike has linked library items directly to classes. This is what I often do as it is fast and makes it easy to understand what code relates to what graphics. It can have it's draw-backs though, for example if you want to runtime load assets from multiple swfs without having to republish them with every code change, and I'm coming round to the idea that it is often better to treat movieclips as "skins", with no code of there own, and have another class that controls them. It would be nice if at runtime you could tell Flash - take this movieclip and make it an instance of this class. That would be cool right, and totally feasible, Adobe engineers?
Code style
  • All Mike's code is beautifully organised, with well-named full-word function and variable names like isOnStage, displayTitleGraphic and onGameOver. This is painfully rare to see, so I salute you Mike!
  • Mike has commented to the point of obsession, which is great, but as his code is so well named and self documenting, most are unnecessary, such as:
    //start the game
    gameArea.start();
    //added to enemies vector
    enemies.push(enemy);
  • Throughout his code Mike has used // double slash comments on his public vars and functions, where he should have used /* slash star */ JavaDoc style comments. This would have allowed code editors like FlashDevelop to give the comment as a hint / tooltip. Really useful when working with an unfamiliar API.
  • There are some slightly strange things with splitting single lines of code over multiple carriage returns, with orphans tabbed weirdly across the page. This is either a Mac/PC formatting issue, or a sign of madness.
Architecture
  • Mike wrote in his blog that he thought he had over-engineered the game and he's not wrong. I ran a little app called cloc (count lines of code) on the folder and it told me that not including white space and comments there are 2420 lines of ActionScript. That's quite a lot when you consider that I managed to get a similar game running in 25 lines of code. Not all the code in a framework needs to be used on every project though, so it's not as bad as it sounds! If you ignore the framework it's only 1644 :) I have a feeling cloc might be over reporting because of block comments, but I might be wrong. So where is all that code going?
  • The GameArea class contains most the game logic, and is a fairly typical well organised game class. I has more white space and comments than it does code though, which I think makes it less readable. Overall this class is very sane though and doesn't include anything particularly wacky.
  • SoundManager doesn't do much - it doesn't even play sounds! Instead it returns and instance of a sound which you can then call play() on. It also contains constants for each sound class name in his library. This might sound like a good idea, but it isn't. Either use the class reference directly or just put the string in your function call. Not every string you ever type has to be put in a constant.
  • For entities there is an inheritance chain of MovieClip > GameObject > PewPewGameObject > Enemy > ChaserEnemy. I've used this kind of approach on many games, and it works up to a point, but it doesn't make your code very reusable, and you often have to hunt around different inheritance levels to find code. These days I use a very simple component system (nothing to do with native Flash components by the way) where functionality is broken down into modules which are owned by objects. So you would have a health component, a weapon component, a position/movement component, a sprite component etc. In Flash we lurve inheritance because it makes us feel like proper programmers, but composition is often a much better approach. This has taken me literally years to come to terms with, so I won't be surprised if lots of people disagree with me. Mike would also be in trouble if he wanted to adapt his game to use Away3D for rendering for example, as he has extended MovieClip. That said, you should always focus on the game you are making rather than worry about "what if" scenarios that will never happen.
  • Mike is using standard Flash events in his game. Again, I've done this many times myself, but since AS3Signals comes out I just use that - but TurboSignals is supposed to be even faster and so probably more appropriate for games. If you want real speed don't use eventing at all - give each entity a reference to your game class and call methods directly on that.
  • Mike has a reusable GameObjectPool class for object pooling, which is nice. However, when you ask it for e.g. a ChaserEnemy, it returns an instance of GameObject which must then be cast back to ChaserEnemy anyway, so he might as well of made an object pool that supports any class type, not just GameObjects.
  • Mike also has the start of some nice util classes for useful Maths functions, but they're not particularly extensive.
Conclusions

Overall PewPew has the hallmarks of a disciplined programmer with good style. Unfortunately it also has many of the limitations that 90% of Flash games suffer, which is a lack of some basic features that you would have seen in games from 20 years ago:
  • A health bar rather than instant death.
  • A scrolling world.
  • A solid world with walls, rooms, corridors etc, rather than just an open void.
  • Basic physics like momentum
  • Ability to pause the game
  • Particle effects for trails and explosions
  • Animated sprites
Good on Mike for releasing his code for public scrutiny - I worry that this is the extent of Adobe's knowledge of game development though. Their gamedev hub http://www.adobe.com/devnet/games/ seems to have been mostly contributed by 3rd parties, and it even includes some advice on such topics as making games with Cairngorm, which is never going to end well. Flash is badly in need of an official gaming API/framework on the scale of Flex. I don't see that happening any time soon, so until then we're all just going to keep re-solving solved problems and repeating the mistakes of the past.




Geometry Wars in 25 lines of ActionScript source code

I recently noticed that Keith Peters' 25 lines competition and all the entries have been purged from the internet, so in case you missed it first time, here's my port of a Geometry Wars style game, with source code below. Click to view.




Here's the source, under free for commercial or non-commercial use MIT license. It gets cut off quite badly by blogger, so you're better off just clicking here to download. To run, just paste it into the timeline of CS4/CS5. I know that's a bad way to do things, but it was the rules of the original competition. If someone wants to make the necessary tweaks to compile it under the Flex compiler, I'd be very happy to post their code. Enjoy!

/**
* 25-Line ActionScript Contest Entry
*
* Project: Trigonometry Wars
* Author: Iain Lobb - iainlobb@googlemail.com
* Date: 27 NOVEMBER 08
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

// 3 free lines! Alter the parameters of the following lines or remove them.
// Do not substitute other code for the three lines in this section
[SWF(width=400, height=400, backgroundColor=0x000000, frameRate=24)]
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;

// INSTRUCTIONS: PLEASE NOTE IT CAN TAKE A WHILE BEFORE ENEMIES APPEAR SO PLEASE BE PATIENT!

// 25 lines begins here!

var enemies:Array = [];

function createOrUpdateEntity(props:Object, entity:MovieClip = null, updateFunction:Function = null, drawCommands:Vector.<int> = null, drawShapes:Vector.<Number> = null, colour:uint = 0x000000):void
{
if (!entity) entity = MovieClip(addChild(new MovieClip()));
if (colour) entity.graphics.lineStyle(1, colour, 1.0, false, "normal", null, null,3);
if (drawCommands) entity.graphics.drawPath(drawCommands, drawShapes, GraphicsPathWinding.NON_ZERO);
if (updateFunction != null) entity.addEventListener(Event.ENTER_FRAME, updateFunction);
for (var thing:String in props) entity[thing] = props[thing];
if (props.array) {props.array.push(entity)};
}

function updateShip(event:Event):void
{
createOrUpdateEntity({x:MovieClip(event.target).x + ((mouseX - MovieClip(event.target).x) / 5), y:MovieClip(event.target).y + ((mouseY - MovieClip(event.target).y) / 5), rotation:(Math.atan2(mouseY - MovieClip(event.target).y, mouseX - MovieClip(event.target).x) * (180 / Math.PI)) + 90}, MovieClip(event.target));
createOrUpdateEntity({x:MovieClip(event.target).x, y:MovieClip(event.target).y, rotation:MovieClip(event.target).rotation, updateFunction:updateBullet, filters:[new GlowFilter(0xFFFF00)]}, null, updateBullet, Vector.<int>([1,2,2,2]), Vector.<Number>([0, 0, 3, 7, -3, 7, 0, 0]), 0xFFFF00);
if (Math.random() > 0.985) for (var i:int = 0; i < 20; i++) createOrUpdateEntity({x:300 + (Math.sin((i/20)*2*Math.PI) * 400), y:300 + (Math.cos((i/20)*2*Math.PI) * 400), rotation:0, array:enemies, updateFunction:updateEnemy, filters:[new GlowFilter(0xFF0000, 1, 12, 12, 4)]}, null, updateEnemy, Vector.<int>([1,2,2,2,2]), Vector.<Number>([0, 0, 10, 10, 0, 20, -10, 10, 0, 0]), 0xFF0000);
}

function updateBullet(event:Event):void
{
createOrUpdateEntity({x:MovieClip(event.target).x + (Math.cos((MovieClip(event.target).rotation - 90) * (Math.PI / 180)) * 12.5), y:MovieClip(event.target).y + (Math.sin((MovieClip(event.target).rotation - 90) * (Math.PI / 180)) * 12.5), rotation:MovieClip(event.target).rotation}, MovieClip(event.target));
if (MovieClip(event.target).x > 400 || MovieClip(event.target).x < 0 || MovieClip(event.target).y > 400 || MovieClip(event.target).y < 0) killEntity(MovieClip(event.target), false);
for (var i:int = 0; i < enemies.length; i++) if (Math.sqrt((((enemies[i].x - MovieClip(event.target).x))*((enemies[i].x - MovieClip(event.target).x))) + (((enemies[i].y - MovieClip(event.target).y))*((enemies[i].y - MovieClip(event.target).y)))) < 10 && this.contains(enemies[i])) killEntity(enemies[i], true);
}

function killEntity(entity:MovieClip, doExplosion:Boolean):void
{
if (this.contains(entity)) { removeChild(entity) };
entity.removeEventListener(Event.ENTER_FRAME, entity.updateFunction)
if (doExplosion) { for (var i:int = 0; i < 10; i++) createOrUpdateEntity({x:entity.x, y:entity.y, rotation:i * 36, updateFunction:updateSpark, filters:[new GlowFilter(0xFFFFFF)]}, null, updateSpark, Vector.<int>([1,2]), Vector.<Number>([0, 0, 0, -10]), 0xFFFFFF) };
}

function updateSpark(event:Event):void
{
createOrUpdateEntity({x:MovieClip(event.target).x + (Math.cos((MovieClip(event.target).rotation - 90) * (Math.PI / 180)) * 12.5), y:MovieClip(event.target).y + (Math.sin((MovieClip(event.target).rotation - 90) * (Math.PI / 180)) * 12.5), rotation:MovieClip(event.target).rotation}, MovieClip(event.target));
if (MovieClip(event.target).x > 400 || MovieClip(event.target).x < 0 || MovieClip(event.target).y > 400 || MovieClip(event.target).y < 0) killEntity(MovieClip(event.target), false);
}

function updateEnemy(event:Event):void {createOrUpdateEntity({x:MovieClip(event.target).x + ((mouseX - MovieClip(event.target).x) / 45), y:MovieClip(event.target).y + ((mouseY - MovieClip(event.target).y) / 45), rotation:0}, MovieClip(event.target))};

createOrUpdateEntity({x:300, y:300, rotation:0, filters:[new GlowFilter(0x00FF00)]}, null, updateShip, Vector.<int>([1,2,2,2,2, 2, 2, 2, 2, 2, 2]), Vector.<Number>([-7.3, -10.3, -5.5, -10.3, -7, -0.6, -0.5, 2.8, 6.2, -0.3, 4.5, -10.3, 6.3, -10.3, 11.1, 1.4, -0.2, 9.6, -11.9, 1.3, -7.3, -10.3]), 0x00FF00);


// 25 lines ends here!

Introducing Gamepad.

Gamepad is a free, open source project by me, Iain Lobb, with the aim of greatly simplifying keyboard input for Flash games. The idea was born out of 2 realisations – first, that since key.isDown was removed from ActionScript it has been more work for game developers to handle keyboard input, and second – that developers, me included, were not working with keyboard input at a sufficient level of abstraction. Trust me, if you make Flash games, you need this in your life. Update: I've had some feedback that it's hard to see the download button on Github, so please CLICK HERE TO DOWNLOAD if you prefer.



What does it do?

Gamepad simulates an analog joystick input using the keyboard. Many times when we access key presses, what we are really doing is pretending that WASD, the arrow keys or some other combination are actually a D-pad or joystick with an X and Y axis, and 1 or 2 fire buttons. Gamepad handles the event capture, maths and other details of this for you, so you only have to think about how you want your game to respond to this input. A detailed explanation follows, but why not just download the source code and play around?



A simple example

First we create a gamepad. It needs a reference to the stage so it can capture keyboard events, and it needs to know whether it is simulating a circular movement space, like a thumb-stick, or a square one, like a flight-stick. This argument is called “isCircle” I’ll get into this distinction later.

var gamepad:Gamepad = new Gamepad(stage, false);

Then in your update / enterFrame function, you simply adjust to the position of your character based on the “x” and “y” values of your gamepad. The “x” and “y” values are always between -1 and 1, so x = -1 would be mean the virtual D-pad is pushed all the way to the left, and x = 1 would mean it would be pushed all the way to the right. I have chosen to use y = -1 as up and y = 1 as down, so that it matches Flash’s screen coordinate system.

character.x += gamepad.x * 5;
character.y += gamepad.y * 5;

And to access the fire buttons, we simply look at the “isDown” property of the “fire1” button.

if (gamepad.fire1.isDown) fire();

That’s it! Your character will now happily walk around the screen using the arrow keys and fire when you press the CTRL key. As Gamepad also has easing by default, the character will also accelerate and decelerate smoothly!

The “isCircle” property

A common mistake that developers make in top-down perspective games, is to allow the player to move too fast diagonally. They say “If the up key is pressed, move up 5 pixels, and if the left key is pressed, move left 5 pixels, so if both are pressed move up 5 pixels and left 5 pixels”. This is wrong! Pythagoras tells us that the speed of their character would now be the square root of five squared plus five squared, which is the square root of fifty, which is about seven. So now their character moves 5 pixels per frame horizontally or vertically, but 7 pixels per frame diagonally. Disaster. Once you know this you can handle it yourself, but Gamepad makes it easy by giving you the isCircle option on creation. When you create your gamepad, simply pass in true for the second argument:

var gamepad:Gamepad = new Gamepad(stage, true);

Now the “nub” of the virtual joystick is limited to a circular area, meaning if you hold the “down” and “right” key together, it will report values of roughly x=0.7 and y= 0.7, instead of x=1 and x=1, and movement speed will be equal in all directions. Typically you would use this option is arena shooters and Zelda-style adventure games, and you may want to use it in scrolling shmups, but that’s a greyer area in terms of “realism”, as your vehicle is already supposed to be moving at a high velocity.

The “ease” property

By default, gamepad will give you a nice easing motion. One advantage it brings is that the player can “tap” the keys to achieve the effect of a half press on an analog input such as the XBOX 360 thumb-stick. Often, though, you won’t actually want to use this. You can easily turn it off by passing in 0, or pass in some other value for more/less responsiveness. Typically you’ll want easing activated for simple games, but in more complex simulations you handle acceleration elsewhere, so you may want it deactivated. To deactivate easing:
var gamepad:Gamepad = new Gamepad(stage, false, 0);

The “autoStep” property.

Gamepad needs to update at the same rate as your game, so that the easing, and the “downTicks” and “upTicks” properties (which I’ll cover later) always keep in sync with your game. If you are simply using Event.ENTER_FRAME for your update, you don’t need to do anything, as this is the default. However, if you have some other system, you should pass in false for the autoStep property and manually call the public “step()” method every time you update.

I advocate using a frame-based tick, and using the “fix your timestep” methodology if you need to stay in sync with real time. This way your game is deterministic, you will have far fewer inconsistencies with collision detection, and you can safely use basic Euler calculations for acceleration. However, I understand that some developers, and some game engines, such as Flixel, use a deltaTime based approach. If you are using a time-based approach, you should use the “fix your timestep” principle with gamepad, by calling the “step()” function an appropriate number of times each update, based on how much time has passed since the user started the game.

The GamepadInput class.

Each Gamepad instance has a set of GamepadInput objects that represent individual “buttons” on a virtual joypad. These are up, down, left, right, fire1 and fire2. However, these do not map one-to-one with keys on the keyboard – one GamepadInput can be linked to one, two or more keys, so that you can easily provide simultaneous alternate control schemes. The classic example would be having both WASD and the arrow keys control your character, so that players can use whichever scheme they prefer without having to set any menu options.

For setting up keys, GamepadInput has the “mapKey” function. It takes two arguments: “keyCode” – an integer representing the key, for which you should use the constants in the handy “com.cheezeworld.utils.KeyCode” class - and “replaceAll” which specifies whether to overwrite existing mappings. If you want to have multiple keys mapped to the same input, pass in false.

In many cases, you will never need to call the “mapKey” function, as there are presets for the most popular configurations in the Gamepad class. These are the functions “useArrows”, “useWASD”, “useIJKL”, and “useZQSD” (which is for the French “AZERTY” keyboard layout, where WASD doesn’t work). All of these methods take a “replaceExisting” argument which specifies whether you want duplicate mappings, as discussed earlier.

Unfortunately, the keys developers use for fire buttons don’t seem to be as standardised, but I have done my best, by providing the methods: “useChevrons”, “useGH”, “useZX”, “useXY” (for German QWERTZ keyboard) and “useControlSpace”. These are all taken from popular Flash games, for example Nitrome’s “Double Edged” which handles 2 players by giving one player WASD for movement and GH for attacking, and the other player arrow keys for movement and chevrons, “<” and” >” for attacking. Gampad’s default: Arrow keys, CONTROL and SPACEBAR should be fairly safe for all players, but there are many, many issues around international keyboards, so it may be advisable to allow the player to set their own keys.

Once you have your inputs set up, you can get information about their state: “isDown” simply tells you if a key is being held down, “isPressed” tells you if a key was pressed this frame/tick/update, and should be used instead of listening for KEY_DOWN events, “isReleased” tells you if the key was released this frame/tick/update, and should be used instead of the KEY_UP event, and “upTicks” and “downTicks” tell you how long the key has been held or released for. Basically, “isDown” is your go-to, but the others are there when you need more info. Generally, you should use the x and y properties of Gamepad for movement, but sometimes you may want to access the D-pad as “buttons” instead, for example using “up” for jump.

The GamepadMulitInput class.

There are also a further set of “buttons” represented by GamePadMultiInput objects. These are special as they aggregate the inputs of multiple other “buttons”. These are “upLeft”, “downLeft”, “upRight” and “downRight”, which let you treat these combined directions as if they were individual inputs on an 8-way controller, and “anyDirection”, which lets you know whether the player is pressing in any direction on the D-pad.

The angle, rotation and magnitude properties.

You may need these additional properties from time to time: “angle” gives you the direction in which the stick is pointed as radians, “rotation” is the same value but expressed in degrees and “magnitude” is the scalar distance of the “nub” from the origin, ignoring the angle. For example, if you set the rotation of a character MovieClip to negative the rotation property of your gamepad, your character will face in the right direction when they move!

The GamepadView class

If you want to visually see what your gamepad is doing, simply create an instance of the handy GamepadView class, and initialise it with a reference to your gamepad and optionally a colour.

var gamepadView:GamepadView = new GamepadView();
gamepadView.init(gamepad, 0xFF6600);
addChild(gamepadView);

GamePadTester and PlatformGamePadTester

In with the source code, you will find two visual “tester” classes. It’s not quite test-driven development, but these are the classes I use to ensure all the functionality of Gamepad is working – they’re also great documentation for Gamepad’s APIs, or could even be the starting point for your own game! If you’re using the Flash IDE simply open GamepadTester.fla or PlatformGamePadTester.fla and publish. If you’re using the Flex compiler you’ll need to create a new project and set the “always compile” / document class to com.iainlobb.gamepadtesters.GamePadTester.as or com.iainlobb.gamepadtesters.PlatformGamePadTester.as.

GamePadTester shows the basics of doing car-style movement and top-down character movement. It also demonstrates duplicate controls, with both WASD and IJKL controlling the character. PlatformGamePadTester shows the basics of a two player platform game, including variable height jumps (although in the end it transpired that these are mostly handled outside of the gamepad class). It also shows how you can create two instances of the same character class with different control schemes, without a single “if” statement or use of polymorphism. Composition FTW!



Final thoughts

Well done, you have made it through all the Gamepad documentation! Please start using it and submit feedback to my blog, or on github. I’ve had versions of this class kicking around for almost 2 years, but I had no idea how much work it would be to actually pull it all together, test and document it to a state where I was happy to release it as an open source project. I have insane new levels of respect for anyone else out there running an open source library. The license is MIT, which basically means you can do whatever you like with it, as long as you don’t blame me when it goes wrong. I’d appreciate it if you didn’t change the package names, and removing the copyright notice is forbidden. There’s a sweet gamepad logo that you can add to your game if you like, but it’s by no means compulsorily, and if you want to hit up the donate button on github, I’m not going to stop you. Enjoy!

Oh yeah, follow me on twitter: http://twitter.com/iainlobb

Open-source ActionScript libraries for creating Flash games

For some reason the incredible power of Open Source is on my mind today. In light of that, here are some open source(ish*) ActionScript libraries I've come across that can help you make games. I haven't tried them all, but maybe you will? *check the licenses before using.

To get code from google code you may have to use a subversion client. On PC use the free TortoiseSVN.
  1. Glaze - super-fast, easy to use rigid body physics engine based on Chipmunk. Prettier syntax than box2D. Demo.
  2. Box2D - uglier (sorry) syntax than Glaze, but has more features (e.g. types of joint), and is better documented.
  3. PushButtonEngine - framework to build games on - doesn't do too much out of the box, but is an admirable attempt to standardise Flash game code structure. Demo.
  4. Collision Detection Kit - Pixel perfect collisions in Flash!
  5. Game Poetry (blog) and CheezeWorld (blog)- these excellent blogs post the source for many of their examples and tutorials on google code.
  6. PixelBlitz - engine for retro -stylee games. Blurb from Photon Storm.
  7. Flixel - another retro-engine. Cool Demo!
  8. PaperVision3D -if you want to go into the third dimension, this is the daddy. Also check out Away3D - it has some features that haven't yet made it to PaperVision3D. Hey, different strokes for different folks!
  9. Jiglib Flash - Physics in 3D!!!
  10. TweenMax - since fusekit was was sadly never ported to AS3, this tweening powerhouse has taken over the whole show. Not only is it great for animating your user-interface, menus etc, I have actually built whole minigames using only this library for all movement and animation. Also gives you quick ways to adjust brightness/contrast etc of images. Only downside is that it is time-based only so won't play nicely with your game if it has a frame-based tick - but this option has been added to the beta, and as you read this is probably now in the live version. If you need frame-based tweening, you can also check out GTween, although Grant is discontinuing the project.
What have I missed? Leave comments!

Creative Commons is a tease!

I think Creative Commons licensing is pretty cool. If Flickr and CC images had existed when I was at university doing interactive art projects and learning design, it would have been a massive help. But unfortunately, I think 2 factors have aligned to make it a bit useless to me. These factors are:
  1. Pretty much everyone is using the non-commercial license
  2. Because of things like Adsense, pretty much everything is commercial
If you post an image on your blog, and your blog has ads, that's basically a commercial use, right? If you make a Flash game with CC non-commercial artwork, you shouldn't even upload it to a portal, as the portal will sell ads around it and so make money. Look at Aral Balkan's stitch-up by Sys-Con as an example of the mess that CC can get things into. Should I even post CC images on my blog? It doesn't have ads, but isn't it kinda part of my business?

Case in point: I love this set of CC sprites by Philipp Lensenn



They are brilliant, but to describe them as FREE as is misleading, because they're under a non-commercial license. Basically they're free, as long as you don't really want to do anything with them.

What's the solution? More people should use the commercial licence. But it wouldn't really be fair to, say, make a hit game and a bunch of money without any going to the artist. A better solution - contact the copyright holder and make a deal to share the money. But that scenario is no different than if the images had no CC license at all.

My solution:

We need to come up with some kind of "revenue share" license, like the royalties radio-stations pay when they play songs on the radio. This way the artist would get a cut, but you wouldn't have to contact them BEFORE you use their work, only once the money rolls in. Would it work? Who knows, but at the moment artists like Philipp might be missing out on a chunk of change because game developers are afraid to use his sprites for fear of breaking the terms of the license.

Thankfully, most code libraries are MIT licensed, which is very permissive, so you don't run into this problem with code. And don't get me wrong - so far I haven't personally CC'd any of my own artwork, but maybe if there was the chance of getting some pocket money from it, I probably would.

PushButton Engine - a game engine for Flash. But will anyone use it?


First off, I recommend you go over to Jeff Tunnel's blog if you want a great read about the business of independent games. Jeff knows a bit about games, having co-founded Garage Games, and his latest venture is PushButton Engine, an open source game engine / library for Flash. I had to re-read the description a couple of times to understand what they're trying to do, but basically it's an MIT licensed AS3 library with pathfinding, physics etc, that they eventually plan to make money from by selling add-ons to developers.

I've thought for a while that Flash gaming needs something like this, to make it is easier for newcomers to create more advanced games. So my first question is - who's the target market? And I guess the answer is I am, since I make my living from Flash games. But here's my problem with that idea - surely anyone who knows enough about both Flash and game development to find this project, learn the API and make a decent game can already apply these concepts through their own code? Potentially this project could save you a lot of development time (for example I wouldn't devote months to creating my own rigid body physics engine) but some of the mechanisms it includes, such as health, teams and spriting are so intrinsic to a game, that I could easily see a developer fighting against the API. There's also a multiplayer API in the works, but that market is already saturated with decent products (although I believe there's still a gap in the market for an unbranded, hosted multiplayer platform).

I'm going to give the engine a good test when I find some time, so stay tuned.

Cool free and open source software for creating Flash games

You can do so much these days using only free and Open Source tools (although I couldn't surive without the Flash IDE). I've been collecting a list of the best ones - apologies to Mac users, some of these are Windows only.
  1. FlashDevelop. Up there with FDT and FlexBuilder as one of the best ways to write ActionScript. I use it together with the Flash IDE (using the IDE for layout, animation and compiling), but it also works with the official free Flex SDK and with unofficial free alternatives MTASC, swfmill and haXe, so you can create Flash games without spending any money at all. If you've ever used Microsoft's excellent Visual Studio, this is the closest thing for Flash developers. FlashDevelop knows the contents of all your classes and provides amazing code completion that seems to know what you want to do before you know yourself. This also gives another good reason to use static typing if you're not already.
  2. Paint.NET. Lots of people know that Gimp is a popular free alternative to PhotoShop, but I much prefer the simplicity and ease of use of Paint.NET - it's easily as good as PhotoShop for doing simple tasks like cropping an image. UPDATE! For a open source tool for creating vector graphics, check out Inkscape - it looks pretty handy if you don't have Illustrator or the Flash IDE. It exports SVG, which I believe you can include directly in Flex SDK projects.
  3. Audacity - for recording and editing your game's sounds. UPDATE! To create wicked retro sound effects check out sfxr!
  4. Blender - a powerful free alternative to 3D Studio Max and Maya. Plug-ins are available to export directly to PaperVision3D and Away3d - sweet!
  5. Subversion, Tortoise SVN and WinMerge - invaluable tools for managing your source code. As a recent convert, I highly recommend you do this!
  6. Easy PHP and Red 5 free server-side environments for developing high score boards and multi-user games, etc.
  7. Eclipse or NetBeans - primarily Java development IDEs (useful when developing SmartFox Server extensions), they also support a range of other languages, such as PHP. The notepad days are truly over - get an IDE!
  8. FileZilla - you'll want to upload your game at some point - I recommend using this!
  9. Firefox. Firefox is a great place to test Flash games, thanks to useful plug-ins like FlashTracer, LiveHTTPHeaders and Tamper Data.
  10. Open Office - use the word processor to spell check your instructions screen, and the spreadsheet application to count your piles of money!

Creative Commons image by KarraMarro

That's your lot! More open-source Flash projects can always be found at OS Flash.