Posts

Showing posts with the label gamedev

Learn Flash Games Development in Cornwall


A few months ago I had the crazy idea that it might be fun to teach an evening course about Flash games, here in Cornwall. Thanks to the awesome people at Truro college, it's happening - and it's starting just 2 weeks from now, on Tuesday the 20th of September 2011. The really great part is that thanks to the magic of government subsidies, the whole 10 week course is just £75 . What, £75 for the whole thing? That's AMAZING VALUE!!! So if you live in Cornwall (or Devon) and want to learn some ActionScript3 programming to make your own computer games - go sign-up.

Flash game development book ideas

I've been mulling over the idea of writing some kind of book or eBook in the future. Rather than being a set of example games like most Flash games books seem to be, it would arm you with the techniques to create your own games, so when you are stuck on a specific topic it is quick to look up.

The book would be almost completely source-code based (with plenty of comments). There would be almost no "waffle" sections of description. It would be more of a look-up (or copy-paste!) technique reference than a traditional "blah-blah-blah" book. Due to this format I think it would be better as an ebook than a dead-tree book. What do you guys think about that?

Anyway, here are my topic ideas. Could you please let me know if there's anything that should or shouldn't be in there?

Input
- Keyboard input and control (from scratch and using Gamepad library)
- Mouse input and control

View
- Top down (+2D Camera)
- Side-on (+parallax)
- Zelda style (+Depth sorting)
- 3D third person (using Away3D)
- 3D first person (using Away3D)
- Mini-map / radar

Rendering
- Blitting
- Using DisplayObjects efficiently

Maths
- Useful maths
- Vector maths

Security
- Site-locking a game

Game engine
- Time steps (basic, deltaTime, fix your timestep)
- Game loop (and pausing)
- Entity systems (inheritance-based, and component-based)
- Object pooling

Collision detection and Reaction
- Circle-circle
- Square-square
- Square-circle
- Line-line
- Line-square
- Line-circle
- Separating axis
- Using hitTestPoint
- Using bitmapdata getPixel
- Using bitmapdata hitTest
- Collision reaction for platform games (player and projectile)
- Collision reaction for top-down games (player and projectile)

Physics
- Top-down car physics
- Platform physics
- Projectile physics
- Using a 3rd party physics engine (Nape)

Environments
- Tile-based techniques
- Using Flash as a level editor - parsing etc
- Creating an in-game level-editor.
- Procedural level generation

Animation
- Bones animation
- MovieClip animations
- Creating your own simple tweening system (+ easing, springs)
- Using a 3rd party tweening engine in-game (TweenMax)
- Sprites sheet / image sequence animations

Audio
- Creating a reusable sound manager
- playing sounds and music
- mute button / volume controls

Gameplay
- Scoring, achievements and saving your game.
- RPG characters - inventory, stats, health, buffs/debuffs.
- Weapon management

User Interface
- HUD
- level select menu
- Main menu
- Shop

Jam games, card games and panini - another great show-and-tell in Plymouth

This is a cross-post from http://explay.tumblr.com/...

Extended Play meetup

We had another friendly and awesome meet-up last night, with demos from Gareth Williams, György Straub, myself and almost Dan Stubbs, as well as a gallery of concept art from some of our other talented members. Gareth showed a badass prototype where you control a snake who has to eat different music samples to build up a beat. Gareth’s demos are great because he invites suggestions for improvements and always gets a good debate going.

Gareth

György showed his work from the last Plymouth game jam, which was an inspired reversal of the tower-defence genre, where you have to defend the helpless monsters from being slaughtered by the evil towers.

Tower Offense

I showed the work-in-progress of my forthcoming game Owl Spin, which will be available to play very soon. Thank you all for your kind words about it, and cheers Alex for being only the 3rd person to play it! I also showed the creative physics toy I made for muzy.com – which you can play with here.
Owl Spin

I also experimented by running a 26-player card game, which actually went quite well. Somehow I even got all my playing cards back at the end of it - what an honest bunch we are! This is how it worked: As everyone arrived I gave each person 2 playing cards and asked them not to look at them or show anyone else. To start the game, I just announced the simple objective – whoever can come to me first with 4 of a kind, wins (a copy of classic movie Gamer). The bar immediately erupted into the trading floor of the New York stock exchange, which was exactly what I hoped would happen, and it was all over in about 60 seconds.

Dan's obscure Japanese card game

The game was inspired by this game design lecture from YouTube and Ryan Creighton’s shenanigans at GDC. Speaking of GDC, Extended Play regulars Ella Romanos and Luke Davies were both out there this year, so hopefully we’ll get field reports from them at the next meeting.
Once again massive thanks to Ria Hartley and the Mutant Labs guys for making it all happen.

Hack the planet

Iain

How to make a whole game in one day

There are game jams and Flash game competitions seemingly every weekend these days. While I don't really like the idea of pinning my eyes open with matchsticks and coding all night, I do like the idea of getting a complete game finished and released in a single day. I sometimes get a day or two of downtime between client projects, and rather than using this time to experiment on bunnies, I've been trying to work out how feasible it is to release 1 or even 2 games in these gaps.

My first couple of attempts have overrun by about double, and still aren't released (I'll keep you posted), but I have learned a few things along the way that I thought were worth sharing. I've also picked the brains of some other friendly developers for some suggestions (you know who you are, so thanks!)

Here's what I've worked out so far:
  • The game can't have more than 1 level that you need to design. So a single maze like Pacman would be ok, but you can't have every level be different.
  • You can't require any complex artwork. You need to use either free art, cheap stock art, art you already have kicking around, or art you can put together in 1 or 2 hours.
  • You need a game engine to start off with. Flixel and Flashpunk might work for you, but I prefer to use my own engine, which I have been revising and improving for well over a year. It's still nowhere near "finished", but I'm not writing much low-level code for each new game.
  • You need a template .fla and/or FlashDevelop template already set up so you don't have to write any boilerplate for Mochi-ads, screen management, preloading etc
  • Your game must have a way of automatically progressing - with either randomly generated levels, or a simple way of getting progressively harder automatically. Players expect to go on a journey of increasing peril, but that's hard to "author" in just a few hours, so automating it is the only way to go.
  • Your game can't introduce you to any programming techniques that you've never done before - e.g. new type of collision detection. Learning a new technique is a fine way to spend an afternoon, just don't expect a game at the end of it.
  • The game must have reasonably similar gameplay to an existing game, so you're not working every aspect of game design out from scratch. If you add even one or two elements to a game that are completely novel, you've done more than most. Combining game mechanics from different games that you enjoy seems like a logical starting point.
  • Don't try to make all the code you write reusable - just get the game done, you can always come and copy bits out of it later.
  • Don't throw your idea out half-way. Once you come up with your idea and started coding, you might as stick with it and do the best job you can to make it fun. Even if it doesn't turn out to be the new Tetris, at least you will have another completed game under your belt.
If you've got any more suggestions and lessons-learned from your own game-jam experience, please post them in the comments.

How to communicate between game objects.

Over on Richard “PhotonStorm” Davey’s blog he proposed a simple way to communicate between objects in your game using a “Registry” a class with static variables storing all the major systems of your game. So, for example if you wanted to create a spray of blood when an enemy is hit, in the enemy’s hit() function you would include the line Registry.fx.sprayBlood(x, y) and the FX object stored in the Registry.fx variable would create the blood spray and handle updating etc.

In the comments on Richard’s post, I pointed out that this isn’t a very object-oriented approach: these are basically global variables by a different name. I have used a similar approach myself on quite a few games projects, and overall it works well and is a quick way of getting things done. I have, however, encountered two problems with it.

Firstly, you can end up with all you code in one huge blob or “god class”. For example, if the FX class is responsible for handling any possible visual effect you would want to create, it could end up getting very big. But, other than academic notions of “good” and “bad” code, there’s nothing especially wrong with having big classes. They may be a bit harder to maintain and reuse, but nothing to worry about too much.

Secondly, using static/global variables as a communication method means you can be limited to having only one “game” in a single project. Now in most scenarios this wouldn’t be a problem, but it’s normally best not to assume you will only ever have one of a particular class of object. I’ve worked on several Flash projects that were collections of minigames in a single swf. Where I was relying on static variables in some of my base-classes and utility classes, I started to see clashes between the different games.

Ok so how do I handle the same problems? Well, say an enemy needs a reference to the player in order to chase after them. Rather than looking up Registry.player, I would just have a “player” variable in my enemy class and I would pass in the value of player when I create the enemy, or once I know the player exists. Or if the enemy needed more than a couple of different references from game in order to work, I would just pass in a reference to the game itself, and let the object access whatever information it needs. As Richard points out, the downside to this approach is that you end up with a lot of references in different places. This isn’t really a problem if you null your references when destroying objects, but it is more work, and you can leak memory if you’re sloppy with it.

Secondly, pretty much everything in my game extends a base Entity class. I have a main Game class that manages all these entities. Game has a method called addEntity(entity:Entity) which adds any new entities I create to the array of entities. Every frame I loop through all my entities and call their public update() function (to pause the game, I just don’t run this loop).

So say I have a SpaceShip object that creates a Bullet object every time it fires. How would I let the game know? I wouldn’t call Game.instance.addEntity() because I may have more than one mini-game that extends my base Game class in a single project. Instead, the base Entity class has a function addEntity(entity:Entity) which dispatches an AS3Signal with the entity value. My game is listening for this signal, and directs the entity to its own addEntity function. You could also use an event to achieve the same effect. Now any Entity can itself create more entities and add them to the game.

How would I use this to solve the problem of creating a spray of blood? I would create two Entity classes. One class is BloodDrop which is a single particle of blood. Every update() it moves based on its speed and falls with gravity, and after 30 frames it fades out and destroys itself. The other class is BloodSpray, which lives for a single frame, and in that frame just runs a loop creating 100 instances of BloodDrop, setting their initial position and speed, and calling addEntity(bloodDrop). Now to add my spray of blood in the enemy’s hit() function, I simply create a new BloodSpray, set its position to match the enemies position and call addEntity(bloodSpray). All the entities know how to update and destroy themselves and are pooled for reuse.

This won’t solve all the communication problems in your game, but it will solve a big chunk of them, and now your code is neatly organised into distinct Entity classes which each perform a single purpose.

Happy coding! I think my next conference/user group talk might have to be one about organising game code :)

Free Flash game source code! Win Adobe Master Collection!



Update 2: The competition has now closed, but please still help yourself to the source code. My original example compiles with the Flash IDE, but Almog Koren has very kindly taken the time to create a version of the game source code for Flex.

I've decided to give away the full source to a Flash game! Here's why - Mark "ickydime" Grossnickle has organised a game development contest to coincide with Stanford University's annual charity "Hackathon". Anyone can enter (that means you!) and the top prize is a copy of Adobe Creative Suite Master Collection (that's all the Adobe software basically) worth $2500.

The theme of the contest is "benevolence" which basically means being charitable and generally a good person. Mark has asked me to help judge the contest, so I can't enter, but I thought my benevolent act could be giving away the source code to a game, to get you started or help you learn game dev.

Ok, so it's not really a full game, but it is a working game engine with a playable character, enemies, bullets and NPCs. You can see it in action here (arrow keys and spacebar) and download the source code here. It compiles in the Flash IDE, so if you want to use the Flex compiler you'll have to hack it a bit.

I originally put the demo together in 1 day, for a session I gave at dotbrighton a couple of years ago, so it doesn't really represent the way I currently structure my game code, but it should be fairly understandable and easy to extend or to copy and paste bits that you need. The character art is Creative Commons non-commercial, grabbed from here (where you can find more characters to use). The tiles are from Game Poetry and are completely free to use. I can't remember where the explosion animation comes from, so you're probably better off not using that one.

In case you're interested, here's more detail on how the code is structured and how I've moved on from this setup: The game has a base Entity class which extends MovieClip. This is great when you're getting started with making games, but becomes very inflexible. What if you want to extend Bitmap for better performance? What if you want to render the game with Away3D or with blitting? For this reason I would recommend composing a separate view class. The code also uses a deep class hierarchy with too many levels of inheritance, and these days I would recommend a modular, composition based code structure. Anyways, in context of this game, the code structure works fine, so enjoy!

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!


BunnyLandMark - a new Flash game benchmark



I learned a lot about Flash rendering with my BunnyMark benchmark, but I felt it was missing a few vital features that would make it a true test of game-specific performance. So I've come up with a brand new test: BunnyLandMark! Once again I created a version using display list Bitmaps, and a version using copyPixels blitting. Here are the new features:
  • a large scrolling world - about 4000x4000 pixels. I chose this size as it is roughly the biggest bitmap you can make in Flash player 10. With a bit more work it is possible to make infinitely large worlds, but this size was big enough for my purposes.
  • Perspective depth-sorting. Bunnies that are further into the scene are sorted to appear behind those that are closer to the viewer.
  • More bunnies - as off-screen bunnies don't need to be drawn, the total number of bunnies can be increased.
And here are the results (INSTRUCTIONS: use ARROW KEYS or WASD to scroll!)
  • The blitting demo can handle 90,000 total bunnies at 30fps, with about 1,900 on-screen bunnies at a time. Blitting was ridiculously fast! That's definitely more bunnies than you require! Depth sorting using blitting is definitely more efficient. Don't forget to scroll with the arrow keys.
  • The display list demo can handle 22,000 total bunnies at 30fps, with about 450 on-screen bunnies at a time. So, in this case blitting is about 4 times faster than the display list, versus only about twice as fast on the previous test.
So here's my conclusion: depth sorting on the display list is pretty slow. In fact, before I came up with some optimisations, it was much, much slower and I couldn't even handle 2,000 total bunnies at 30fps. In my first iteration I used setChildIndex to order the display objects, ignoring those that are offscreen. But when you think about thousands of bunnies slopping about in the display list, you can guess that this was incredibly slow. I don't know how the display list works behind the scenes, but it doesn't like you changing depths. The trick I came up with was to loop through and removeChild every bunny, and addChild back only the ones I need on screen. This meant my displayList was much shorter and so all my display list operations were much faster. I still think 450 on-screen, depth-sorted entities at a time is going to be plenty for most games, but I can definitely imagine a few scenarios where it wouldn't be enough.

Ok, over to you now readers! Please test and report any differences in frame rate you get. I'm particularly interested to see if Mac Safari performs as woefully on this display demo as it did on the last. I have updated the source zip to contain all the bunny demos.

Windows Phone 7 for Flash Developers, Part 1


As I write this I am in possession of a Windows Phone 7 developer handset, the problem is I don't know quite what to do with it yet. I think WP7 seems like a well thought-out platform, hence my interest in developing for it, but as a completely new technology, it's hard to know exactly what the best strategy for app and game development is. Here are some random facts and thoughts about the platform. (Since I first posted this, Mike Ormond from Microsoft has emailed me with some more definitive answers, so I have updated the post to reflect this).
  • Let's get the bad news out of the way first: there is currently no support for 3rd party tools like Adobe AIR and Unity3D. Although Mike says "there will almost certainly be support for 3rd party tools" in the future, he couldn't give any specifics about what those might be, and as always with these things, it's impossible to know whose court the ball is in.
  • The phone's browser works well, but doesn't support either Flash or HTML5 content at present. This may well change, but nothing is confirmed or has been officially announced by Microsoft for either HTML5 or Flash. The lack of HTML5 support really surprised me, considering how enthusiastically Microsoft are supporting it with IE9.
  • Ok, now on to the good stuff. You can develop apps with Silverlight and games with XNA. You can only develop on Windows 7 or Vista (SP2), and in fact for the XNA emulator to work you need Windows 7 and a recently produced graphics card, so I can only test games on my device, not on the emulator. Installing the free developer tools takes about 2 hours - you get special versions of Visual Studio 2010 and Blend 4. Visual Studio is good, although 2010 uses WPF and doesn't feel as punchy as 2008 did on my machine. The auto-completion is great, although it doesn't have all the handy keyboard shortcuts I'm used to in Flashdevelop. Blend is a design tool similar to Flash Catalyst, but I haven't really played with it yet.
  • To release apps to the app store, you need to pay an annual fee of about £70/$100. This fee also allows you to release games on Xbox 360 indie games. Xbox shares 95% of the same XNA apis with WP7, so it would be relatively easy to make a game on one platform and port to the other - you would just need to account for input and screen size. I have paid my fee, so I will definitely release something for one of the two platforms this year. I've always wanted to do a console game, so I will probably try to do something that I can release on both.
  • Silverlight is a high-level, vector based scene-graph with standard components like buttons, menus etc, a bit like Flash + Flex. Silverlight could theoretically be used to make games as well as apps, although I don't know what the graphical performance would be like. If you make a game with Silverlight, you can still make it show up in the games section of the marketplace rather than with apps. The phone UI has nice, consistent styling and fonts, and by default your Silverlight apps match this styling automatically.
  • XNA is a fairly low-level game/graphics library which exposes hardware accelerated 3D rendering and 2D blitting. I've not benchmarked it yet, but it's really fast. XNA has no scene-graph or concept of a sprite, so if you are used to working this way in Flash, some things are going to take you a lot longer. See this post for what I think are the benefits of a scene-graph, but the main difference for me is not being able to create hierarchies of objects, for example a player object containing arm and leg objects that can be manipulated relative to the position of the player. I'm going to investigate some way of recreating this functionality myself.
  • The resolution is really high (800x480) on a pretty small screen, so if I want to use any of my pixel art characters from other games I will probably have to look at double-scaling everything. Otherwise, a 32x32 pixel character is only about 2mm on the screen. Mike tells me that a lower resolution device may be available in the future, but I'm not sure how existing apps would be scaled scaled down to fit a lower resolution, and I could potentially see that causing problems.
  • There are paid apps and free apps, just like iOS, although apparently you can only submit 5 free apps per year before you have to pay an additional fee - presumably this is to stop shovelware, so may not be a bad thing.
  • Like Apple with iAds, Microsoft are running there own advertising network. Currently this feature is only available in the US, although is set to come to other countries in early 2011. However, it ONLY supports Silverlight apps, not XNA, so isn't much use to me anyway. Mike confirms that it is unlikely XNA ads will ever be supported, although he points out that other networks are allowed, so if Admob want to add XNA/WP7 support, they can. Will they? Who knows.
  • Games have a 2-tier system where the big studios are able to have Xbox Live branding and support, such as achievements, and indie game are not. I understand why they have done this, but as an indie it does put you at a disadvantage to the big boys.
  • Paid apps support a trial mode, which I think is a really good thing for both users and developers. Users can try an app out before they buy it without the need for the developer to create a separate "lite" version. You just specify which features should work in trial mode or how long the trial should last. This does create a bit of a dilemma for a game developer though. Many Flash and iPhone games (e.g. Cannabalt) have a play time of just a few minutes. If you are able to get this full game experience from the trial mode, there is no incentive to buy the game. And with no ad network support at the moment, I don't see any way to monetize a short-form game. The way to make a profit would seem to be to make a long form game with a very engaging/adictive first few minutes as a trial mode.
  • In terms of fee-for-service work, the Silverlight side is likely to be dominated by existing .NET/Silverlight developers, of which there are many. I think it is unlikely that day-rates for Windows Phone 7 development will reach the enviably lucrative heights of iOS. As the market leader, iOS apps are in very high demand from paying clients. At the same time, the superficial strangeness of Objective-C and requirement to use a Mac reduces the developer base and greatly limits supply. This creates a perfect storm of high developer costs that I doubt we'll see in the more abundant world of .NET developers, on a new platform with many fewer potential customers. Gamedev, of course, is really a quite a different set of skills, which many Flash developers have in abundance, so if a market did emerge for branded games, this could be a good area for Flash developers to look into.
Taking all this into account, I think the opportunity for Flash developers who want to branch out into the WP7 space will be to bring their creative and gamedev skills to the paid games market, but it would have to be with long-form/multi-level games like Angry Birds, Trainyard, Warlords etc. And coming up with killer game ideas like those, while implementing on a brand new system, isn't going to be easy. Windows Phone 7 seems like a decent phone platform with good developer support. Like with any platform though, the killer idea needs to come from you, and for now, I'm still trying to think of mine.

In part 2 of the series I will be testing rendering performance by porting BunnyMark to Silverlight and XNA!

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?

In defense of MovieClips, Sprites and the display list (...the case against blitting?)



“This is why I always run a raster pipeline. The DisplayObject API is a trick played on the gullible and the trusting…” — @bengarney
Ben Garney is a very smart game/engine developer with a background in C++ and known for developing the Torque engine, who has now moved into the Flash world with Pushbutton Engine and games like Social City. I come from the complete opposite direction. I’m a Flash guy with a background in quick turn-around, design driven creative Flash projects, who now focuses on game development. This difference in backgrounds, and dare I say *ideologies* is why I thought I should write a response to Ben’s recent post about blitting, and stick up for the display list a bit. If you haven’t read Ben’s article, I suggest you go do that, but for the sake of clarification, blitting is basically using copyPixels to manually draw your graphics to a single bitmap data object that you display via a single Bitmap object on the stage.

Firstly, there is a lot of truth in what Ben says. Here are the advantages I see for blitting:
  1. Renders faster if you have thousands of sprites.
  2. Although Ben didn't mention this, if you use the Flixel, Flashpunk or Pushbutton engines you get some other game engine functionality for free, although most of the benefits of e.g. Flixel are nothing to do with the fact that it uses blitting.
  3. Erm...
Now here are the advantages for using MovieClips, Sprites and Bitmaps in the native Flash display list:
  1. You get rotation, scaling, alpha, filters and colour effects for free. Want to add a glow or blur to something? It’s one line of code, and adds no filesize to your app. If you use blitting you have to somehow prerender all these effects, either as pngs that will increase the filesize of your game, or prerender at runtime, which will add a lot of complexity to your code and add to your development time, and in the cutthroat world of Flash games, time is money. If you combine the display list’s built in effects with an engine like TweenMax, you can make amazing animated effects in just a few lines of code.
  2. You can work easily with interactive designers. Most creative agencies have designers who are experts at using the Flash IDE to create beautiful layouts and animations that you can easily breathe life into with ActionScript. If you are working from flat PSDs for all your assets, you will spend a lot of time laying screens out in code, which is something you never really want to do. The reason Flixel etc are never used on advergames, e-learning games or other client projects is that there is no workflow for designers to add their branding magic.
  3. You get mouse events. You can easily create buttons and more complex interactive elements with complex hit areas. Now in a game it is very possible to use blitting on your gameplay area but still use the display list for all menus/gui, and I would definitely recommend this option over blitting *everything* like Flixel does. However, sometimes you want to have interactive menus and buttons inside the gameplay area, in which case it will be much easier for you to use the display list in your game rather than recreate all that functionality from scratch inside your blitted area.
  4. You can nest things inside other things. This is very useful for things like menus, but is also very a great way to create dynamic animations that can be altered at runtime. For example, if you have an animated character holding a weapon, if the weapon is a sprite inside the character sprite, you can easily swap out the contents of the weapon sprite to change weapons. If you are using blitting, this feature will be time consuming to recreate.
  5. It’s not as slow as people think. If you are just moving Bitmap objects around in the display list you will easily be able to have hundreds of sprites on screen, in a typical game. And as only displayObjects within the viewable stage area are drawn, you can actually have a game play area with thousands of sprites, so long as you can only view hundreds at a time. Turning off mouse interaction for the display objects (mouseChildren = false, mouseEnabled = false) makes everything run significantly faster too. I have a demo with 40,000 tiles scrolling on the display list smoothly at 120fps – as Flash only renders those tiles inside the viewable area of the stage. You can also use a hybrid blitting / display list approach by having a Bitmap objects on the display list which you animate by changing the value of the bitmap.bitmapData property. This is very fast and you still get all the advantages of the display list effects. The best of both worlds!
So ultimately it becomes a question of how much rendering speed ya needs versus how much development time ya gots (read that last sentence in the style of the Clint Eastwood). From what Ben says about Social City, it looks like a poster child for blitting – it’s a scene with thousands of sprites drawn at once (although Ben’s claim that his display list tests were running at less than 1 frame per second suggests to me that he had not correctly optimised by turning off mouse interaction). Either way, display list *will* always render slower for a thousand sprites. But pretty much every Flixel game I have seen would have run perfectly using the display list. Ben says that the display list is the darkside of the force. In equally mischievous tone, I propose that blitting is for people who don’t actually like Flash, and they see everything that makes it unique and interesting, like the excellent Flash IDE and the vector display list renderer, as a negative. I will get some benchmark demos of both approaches up soon. Of course display list will lose, but it won't be as bad as people think. Comments appreciated!

Indie Flash Games 101

My buddy Adam, who has just started teaching interactive media at university in Denmark, emailed me some questions about how to get his students started with publishing their own indie Flash games. These days I can't write anything without making it into a blog post, so here's my getting started guide:

What technical issues should students be aware of?
- You need both a copy of Flash Professional (CS3, 4, or 5) AND a code editor. If you are on Windows download FlashDevelop - it's free. Otherwise try FDT, InteliJ IDEa or FlashBuilder, which all have free/cheap options for students/beginners.
- Use ActionScript3, Flash player 9 or 10.
-If you are confident with programming and want to make more advanced games in a short space of time, consider using Flixel or Box2D.
- Filesize should be less than 8MB
- Dimensions should be width: 400-720 pixels, height: 300-600 pixels.
- Game should be a single self-contained swf file.

What are the top sites to submit a game to, and how can they judge how good their game is?
- Kongregate - Signs of success: score 2.8 or higher on the user rating, get more than 500 plays, get some positive comments. Kongregate audience are very particular and are much more forgiving to long form fantasy RPG type games than other genres. Expect mini-games to get a roasting / be ignored. Getting featured on the front page or winning any weekly contests very unlikely for a beginner. Game can include Mochiads, which Kong will automatically disable, and instead give you nice share of their ad revenue.
- Newgrounds - Signs of success: score 3.2 or higher on the user rating, get more than 1000 plays, get some positive comments. Newground audience are lovable scamps with an open mind about any type of game. Front page feature unlikely but getting featured on any page or finishing in the daily/weekly top games is something to aim for. Game can include Mochiads.
- FlashGameLicense - in the current FGL market, beginner and mini-games are unlikely to sell at all, but it's still worth investigating this site.
- Add the Mochi analytics APIs, (and mochi ads obviously) and submit to Mochi distribution to see how a game does virally. Signs of success: 5000 plays, large number of sites featuring game.
- More portals can be found on this handy list.

What should students aspire to?
- Front page of Digg.com
- featured on mainstream games blog e.g. Kotaku.
- featured in print publication e.g. Edge, .net
- Front page on Newgrounds or Kongregate
- Millions of plays across various sites
- attract sponsorship from big name e.g. ArmorGames, Kongregate
- players produce fan art

Hope this is useful to someone. Remember not to take the negative criticism from comments too personally. Learn from it and move on to your next game!

Understanding Game Time Steps - Your 3 Options

I was just answering a question over at the gamedev Stack Exchange beta site and I realised I was pretty much writing a blog post about time steps for games. How you handle your time step has big implications on how your game architecture needs to be set up. There's a lot of confusion and misinformation in this space, but I think I've pretty much got my head around it. Here are your 3 options:

Option 1 - Do Nothing

Do nothing. Attempt to update and render at a certain interval, e.g. 30 times per second. If it falls behind, let it and don't worry. The game will slow down into jerky slow motion if the CPU can't keep up with your game, but there will be no jarring jumps across the screen. This option won't work at all for real-time multi-user games, but is fine for single player games and has been used successfully in many games.

Option 2 - Delta Time

Use the delta time between each update to vary the movement of objects. In Flash this is just a matter of calling getTimer() and deducting the value of the previous frame's getTimer() call. This tells you how much time has elapsed since the last frame. Now you can factor this value in to all your maths. Great in theory, especially if nothing in your game accelerates or decelerates, but just moves at a constant speed. In practice, many developers implement this badly, and it can lead to inconsistent collision detection and physics. It seems some developers think this method is easier than it is. If you want to use this option you need to step your game up considerably and bring out some big-gun maths and algorithms, for example using a Verlet physics integrator (rather than the standard Euler that most people use) and using rays for collision detection rather than simple Pythagoras distance checks. I asked a question about this on Stack Overflow a while back and got some great answers:

http://stackoverflow.com/questions/153507/calculate-the-position-of-an-accelerating-body-after-a-certain-time

Option 3 - Fix Your Time Step

Use Gaffer's "fix your time step" approach. Update the game in fixed steps as in option 1, but do so multiple times per frame rendered - based on how much time has elapsed - so that the game logic keeps up with real time, while remaining in discrete steps. This way, easy to implement game logic like Euler integrators and simple collision detection still work. You also have the option of interpolating graphical animations based on delta time, but this is only for visual effects, and nothing that affects your core game logic. You can potentially get in trouble if your updates are very intensive - if the updates fall behind, you will need more and more of them to keep up, potential making your game even less responsive. I'm now going to try and explain how to implement this in Flash - concentrate!

Firstly, one implication of this approach is that you cannot rely on ENTER_FRAME to update each object. You must have a single ENTER_FRAME for the whole game that loops through each object and calls a public update() method. Each ENTER_FRAME tick you may have to call these update functions 0, 1, 2, 3 or even more times in order to get back in sync with real time. To work out how many times to update, you call getTimer() and take away the value of getTimer() from the start of the game. This tells you how much time has elapsed since the game started. Now work out how up-to-date your game logic is, by multiplying the number times you have called update (you'll need to keep track of this) by the length of 1 frame (e.g. 1/30 seconds for 30fps) - this is how much time has passed in your game world. Compare how much time has elapsed in real life to how much has elapsed in the game world. If they are different by more than 1 time step (e.g. 1/30 seconds) then call update until they are in sync to within less than 1 time step. This may seem pretty full-on, but it's really pretty simple - I will try to get a code demo up soon.

Personally, I like Option 1 - Do Nothing, when I can get away with it, and Option 3 - Fix your Time Step, when I need to sync to real time. I respect that Option 2 can be a good option when you know what you're doing, but I know my limitations well enough to stay well away from it.

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.




Gamepad ported to Processing / JAVA

Gamepad, my opensource keyboard input utility, has received a great reaction so far, with many retweets, over 1000 views, and some great partnerships with other libraries in the pipeline. And now it's not just for Flash, because Michael Heuer has ported the whole project to JAVA for use with processing. So, if that's how you get down, go check out Gamepad for Processing on Github. Big thanks to Michael for taking the time to create this.


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

Creating Successful Flash Games (notes and slides)

Last night at The London Flash Developers and Designers Meetup Group I gave a talk called Creating Successful Flash Games. I think it was the most fun I've had doing a talk so far, and I've had some really lovely feedback:
"Great evening at South Bank Uni listening to Iain talk flash games. Always nice when you can tell the speaker is passionate about gaming."
"Great talk! It gets better and better. All I can say is thanks,
I learned a lot from your experiences. Also, you explain things really well, you empathize with the situation you are trying to explain. "
I love doing these speaking things so if you are organising a conference or user group I'd love to hear from you - hit me up at iainlobb@googlemail.com.

Anyway, as promised last night here my slides/notes. You can download them as a pdf or simply read them below. It's not the same without my jumping about and "acting" as one person described it, and a lot of the content I just did from memory, but there should still be something useful there. Anyway...

Design or Development?

Designers do graphics and developers do code?
But in games
  • artists do graphics
  • developers do code
  • designers make it fun!
So maybe we need a better definition.
  • Developers solve technical problems
  • Designers solve human problems.
So we all do a bit of both.

With experience and better tools, things move from the development side to the design side. Which makes the whole process more fun!
  • var sound:Sound = new ShotgunSound();
  • var transform:SoundTransform = new SoundTransform();
  • transform.volume = 0.5;
  • var channel:SoundChannel = sound.play(0, 1, transform);
Vs.
  • SoundManager.play(ShotgunSound, 0.5);
What are games?
  • Games are about the relationships between objects in space.
  • ... but videogames layer-on images, characters, narratives, sound and music.
  • Historically, most games are multiplayer (chess, football etc).
  • Videogames allow the computer to take on the role of opponent.
  • ... but multiplayer is still more fun!
Goals
  • Collect objects
  • Kill enemies
  • Reach locations
  • Match objects
  • Solve puzzles
  • Make friends (real or virtual)
  • Pwn noobs
  • Most games use a combination.
Constraints
  • Time limit
  • Health
  • Lives
  • Ammo
  • Money
  • XP / Experience
  • Inventory limit
  • Doors & Keys
  • Enemies, obstacles & puzzles
Modes of interaction
  • Control a single avatar
  • Command multiple agents
  • Manipulate objects
  • Match rhythms
  • Create entities
Input

Flash sucks at input!
Mouse
  • Left button, context menu, wheel.
  • sprite.mouseX and sprite.mouseY
  • No wrapping or moving the cursor.
Keyboard
  • KeyboardEvent.KEY_DOWN and KeyboardEvent.KEY_UP
  • Limited simultaneous presses.
  • CTRL, ALT and SHIFT are a no-go area!
Gamepad.as

Here I come to save the day!


Based on analog joystick input.
  • var gamepad:Gamepad = new Gamepad(stage, true);
  • character.x += gamepad.x * 5;
  • character.y += gamepad.y * 5;
  • if (gamepad. fire1) { fire() };
Use arrow keys, WASD or custom settings.
Duplicate keys and fire rate coming soon.

Mousepad.as
  • Coming soon...
  • For games where you move or aim with the mouse.
  • Similar abilities to Gamepad.as, but for mouse.
Top-down View

True top-down
  • Easy to rotate sprites.
  • Good for driving games etc.
Zelda-style
  • Art is drawn with false perspective.
  • Better for characters.
  • ... but you have to draw every angle.
Movement can be:
  • compass-direction (for characters)
  • or tank-style (for vehicles)
Side-on View
  • Great for showing humanoid characters.
  • Typically involves jumping around implausible vertical spaces called “platforms”.
  • Variable jumps.
  • Double-jumps.
  • In-air movement control.
  • “Brawler” view like Final Fight or Castle Crashers is somewhere between Top-down and Side-on.
Isometric View
  • Graphics are drawn from a fixed 45 degree angle.
  • Good for Sim games, puzzles and driving games.
  • Great for showing buildings – see eBoy.
  • Confusing for player movement – which way is left?
First person View

Either using a 3D engine or pre-rendered from a fixed perspective.
Great for shooting, exploration and puzzle games.

There are other views
  • Follow-cam (basically the same as first person)
  • 3rd person 3D camera (can track players)
  • etc
3D

All games are 3D.
  • A top down game where you can jump.
  • A parallax background behind a platform game.
  • So my new game engine is 100% 3D.
...but most aren’t.
  • Gravity means we live on a 2D plane.
  • We need a definite idea of up and down.
  • 2.5D works really well.
3D

3D is really hard, but the basics are easy:
  • var scaleRatio:Number = focalLength / (focalLength + z3d);
  • y = baseY + (( -z3d + y3d) * scaleRatio);
  • x = baseX + (( z3d + x3d) * scaleRatio);
  • scaleX = scaleY = scaleRatio;
Luckily libraries are available to make your life easier.
3D art is more labour intensive to create, but is much more flexible. Animation is harder still.
If you’re serious, consider switching to Unity3D.

Collision Detection

Built in
  • sprite.hitTestPoint()
  • sprite.hitTestObject()
  • bitmapData.hitTest()
Pythagoras
  • dx = sprite1.x – sprite2.x;
  • dy = sprite1.y – sprite2.y;
  • distance = Math.sqrt((dx*dx)+(dy*dy));
Bounding box (sorry conversion to HTML has broken this)
  • if (bottom1 <>
  • if (top1 > bottom2) return false;
  • if (right1 <>
  • if (left1 > right2) return false;
  • return(true);
More advanced:
  • Line-line
  • Line-grid
  • Line-circle
  • Point-grid
  • Circle-grid
  • Point-polygon
  • Polygon-polygon
  • And many more!
Physics

Gravity
  • speedY += gravity; y += speedY;
Bouncing
  • speedY *= -0.9;
Beyond that it gets really, really hard!

Luckily there are libraries to help you
Tile Grids

Present since the earliest games.
A neat simplification for games.
  • var gridX:int = sprite.x / tileSize;
  • var gridY:int = sprite.y / tileSize;
  • var grid:Array = [[“air”, ”air”, “trap”, “platform”], [“air”, “platform”, “air”, “air”]];
  • if (grid[gridX][gridY] == “trap”) {killPlayer()};
Helps with collision detection, path-finding, level design.
Powerful but restrictive.

Blitting

Working directly with image data rather than using the standard display list.
  • bitmapData.copyPixels()
  • bitmapData.draw()
  • Matrix transformations
  • “buffers”
  • graphics.beginBitmapFill()
  • graphics.drawTriangles()
  • Can be faster, but harder to do rotations etc
Libraries
Art

Flash is very flexible and can handle a range of styles.
  • Hand-drawn
  • Pixel-art
  • Cell-shaded cartoon
  • Painted
  • 3D rendered
  • Photographic
It normally doesn’t hurt to make your game look like a game though.

Animation

The best animation is done by hand.
Hand-draw frames and position manually.
Tweens are normally better off in code.
  • object.x += (target.x – object.x) * 0.3;
Tweening libraries save you many hours of work.
Tuning and polish
  • Weapon strength, time limits, enemy speed etc in easily modifiable variables or XML.
  • Jump height needs to match level design.
  • Particle effects, flashes, tints, screen shake
  • What happens when you walk into a wall? Do you slide, walk on the spot, flatten against it?
  • Good usability on U.I. – pictorial not text.
  • Freedom of movement, expressiveness, “feel”, playability
You need a hook
  • You need something which is unique to your game.
  • Hook, Unique Selling Point (USP), gimmick, or twist.
  • Character, weapon, unit type, mode of interaction, game mechanic.
  • Don’t just make a clone with different graphics.
  • If you’re going to copy something, work out what about it you’re actually trying copy.
Sound & Music

Can turn a good game into a great game.
Very clunky built-in support.

Fade-in/out, pause, mute, loop, etc:
For sound effects try:
Audacity, Sony Acid Music, Garage Band etc
Record your own!

Instructions
  • Players don’t want to read instructions.
  • Animation works better.
  • Walk-throughs or tutorials are even better.
  • Best of all is no instructions needed.
  • Keep the controls on screen all the time.
Saving

Really easy!
  • sharedObject = SharedObject.getLocal(“game");
  • sharedObject.data.score=9232;
  • sharedObject.flush();
Use “slots” to allow multiple saves.
Progress can also be saved to a server.
Or via level codes.

A.I.
  • Be pragmatic and come up with simple rules that work.
  • You’re not making chess computers here - don’t code the perfect enemy.
  • Enemies are generally slow and weaker than your player – even their bullets move slower!
  • A* path-finding etc is hard, but examples are out there.
Multiplayer

Easy to do 2 players on one computer.
Networked multiplayer adds a new level of fun but greater complexity.
Most solutions require you to have your own server:
But not all!
Turn-based and “deterministic” games require little or no server code.
Real-time games require some Java, JavaScript or C# code on the server.
Server-code may also be needed to stop cheating.
Multiplayer games are less common but command higher prices as they encourage repeat plays.

Business Models

Sponsorship.
  • Portals pay to add their branding to your game and add links back to their site.
  • Exclusive or non-exclusive licenses.
  • “Site locks”
  • Performance deals.
  • £100 – £10,000 per game.
  • http://www.flashgamelicense.com/
Advertising.
Sales.
Client briefs.
  • They pay you money and you make what they tell you to.
  • Steady income but less creative.
  • No chance of getting rich.
  • Can still be cool: e.g. Zwok!, Meta4orce.
  • £1000-£100,000
Thanks!
Double Edged - Nitrome - Play Free Games
Play Don't Look Back, a free online game on Kongregate
Fancy Pants Adventures | Armor Games
Play Boxhead: The Zombie Wars, a free online game on Kongregate
Xeno Tactic - to play free online games
STACKOPOLIS :"The most addictive game since Tetris!"- LCLFC
---===+==O[ Two KingdomS ]O==+===---
BBC - Switch Meta4orce - Launch
Escape game - Flash game
BBC - Switch Meta4orce - Launch
Play Red Remover, a free online game on Kongregate
Shaun the Sheep - Games - Home Sheep Home
Muzer's Blog
Car Drive On Terrain « Muzer's Blog
CANABALT
Play Pop Pirates, a free online game on Kongregate
Twin Shot 2 - Nitrome - Play Free Games