Thursday, 16 December 2010

Game performance benchmark BunnyMark ported to HTML5!



BunnyMark is the benchmark that's taking the world by storm! Just to prove that javascript is easy and a wittle baby language I have ported BunnyMark to HTML5. Results confirm that HTML5 really is one better than HTML4. Lightning fast with 3000 bunnies in Chrome, Firefox4, horrible in Firefox 3, non existant in IE678. Click here to view, source is on "view source". Other browser users (IE9, Safari, Opera) please report performance in the comments.

Don't miss the Windows Phone 7 and Flash versions, and BunnyLandMark for Flash, which I haven't got round to porting yet.

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!


Wednesday, 10 November 2010

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.

Monday, 8 November 2010

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!

Thursday, 4 November 2010

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?

Wednesday, 3 November 2010

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!

Thursday, 28 October 2010

AdvancED Game Design with Flash – Book Review

Lovely, lovely Friends of ED were kind enough to send me a copy of AdvancED Game Design with Flash by Rex Van Der Spuy. Just because they gave me free stuff, it doesn’t mean I’m going to give this book an easy ride though! This book has lots of good things and a few not so good things, as I will describe.

Let’s start by getting one thing out of the way – this book has almost nothing to do with game design. There is no mention of game design (as I understand the term) until Chapter 7, where Rex gives a few pages of good advice. The other 700 or so pages of the book are about game programming/development/architecture. (To be clear, my understanding of "game design" is: deciding what happens in your game and tuning the game mechanics to make them fun).

The best thing about this book is that it is very comprehensive, covering pretty much every hurdle you will meet when building a Flash game, including an extensive looks at collision detection, which is probably one of the hardest parts of game development if you aren’t using an engine like Unity3D, Box2D or Flixel. There is an explanation of many alternative methods such as bitmap collisions (including destructible bitmaps!), axis-aligned bounding box (AABB), circle, line and “separating axis theorem” for more complex shapes. It also shows you how to do “spatial hashing” which is a “broad-phase” technique for reducing the number of collision checks you need to do, which is very useful. Unfortunately it doesn’t include the “quad-tree” technique, which is the one I need to get my head around at the moment.

Another section you may find useful is the analysis of blitting. I think the benefits of blitting are a bit exaggerated, but this book takes a very even-handed approach, explaining when they will be useful and when they won’t. It also includes some benchmarks and shows you how to make your own, which you should ALWAYS do if you are making “optimisations”. Don’t believe a word that Rex, myself or anyone else tells you about optimisation without testing it yourself!

I’m not a huge fan of how the author organises his code. He’s gone for an MVC approach throughout the book, and even though this is a road I’ve been down myself many times, it’s not one that I would currently recommend (for the record, I favour a game object composition approach like you get in Unity3D). In general the code style is decent, with well named variables and plenty of comments. There are some places where the code could have been made both faster and more readable by greater type safety and less use of the dynamic properties on objects, movieclips and arrays. There are some places where variables are not well-named, for example calling a function “ln()” rather than “leftNormal()”. In the age of auto-completion there is really no need for abbreviated function names, but this book is by a long way not the only place you will find them.

Here is my most major criticism the book: for physics/movement Rex is using his own vector and “verlet” techniques, and I am dubious about both. I’m not an expert on integrators, but I’m very skeptical that Rex’s approach really is verlet at all. It seems to me that he’s using the standard Euler technique that most Flash developers use, but just storing his data in a different way. I would love to be wrong about this one, so if anyone has read the book and has a good understanding of verlet, please leave a comment. The vector class the book uses is also non-standard. The usual implementation of a vector has just an x and y position, and some methods to manipulate it such as add, multiply, divide, rotate, dot-product etc. The book’s vector class has these methods, but it stores two sets of x and y values – a start point and an end point. It all still works fine, it’s just not how it’s normally done.

On points like this I find it very difficult to draw the line between what is just differences in style and what would be considered “best practice”. As I already knew most of the information covered in the book it’s easy for me to worry too much about things I just do a bit differently. If you have never used these techniques, any implementation will be very useful to know. Ultimately, if it gets the job done, then it’s fine, and Rex’s implementation definitely gets the job done.

Some other useful explanations in the book include playing sounds, pathfinding (including a really good explanation of A*) and a full tile-based platform game engine. After my talk at Flash on the beach I had many requests for my source code, but as all my demos were built on my non-open-source game engine, I couldn’t share them. I would happily recommend this book to any of those people as it includes the vast majority of the code you need to make any of the demos I showed, including driving games and platform games.

Overall, I think that if want to do some more advanced Flash games and you don’t know where to start, this book would be a great place.


Friday, 15 October 2010

Cornwall Digital Meetup - Wednesday 20th October 2010


Another shout-out for people in Cornwall - do not miss the first meeting of Cornwall digital meetup group on Wednesday 20th October 2010 at Blue Bar in Porthtowan, details are at: http://www.meetup.com/Cornwall-Digital/

Tuesday, 12 October 2010

Games meetup in Plymouth: 1st of November 2010


Ok this is a pretty niche post, so as soon as you answer no to any of these criteria, you can happily stop reading! If you live in Devon or Cornwall, and are into game design, development, art, music, interactivity or any other related field you can now hang out with kindred spirits, have a beer and get excited about making games. There is a new monthly meetup in Plymouth starting 1st of November 2010. The guys from the awesome Mutant Labs and Remode studios will be there, so will Korash who organises the Extended Play games festival, along with a bunch of students and of course me! You can sign up to it on Facebook http://www.facebook.com/event.php?eid=109217385808574 - or if you hate facebook that much, just email me and I'll send you the details when they are finalised. If you live in Cornwall I will be driving up so I can even give 4 people a lift. You now have no excuse not to go!

Friday, 1 October 2010

Flash on the Beach 2010 – This guy’s experience.


I’m writing this on the train home from Flash on the Beach. I should probably be coding a game like I did on the way to the conference, but I’m finding that after sensory overload from 3 days of sessions, a few late nights and the terror of doing two(!) sessions on stage, my brain is unable to do code right now.

My main session seemed to go very well, although I’m gutted for all the people who couldn’t get in because it was so packed. The demos from the session are already available at DullDudeGames.com/game-designer and I’m going to add a transcript of what I said and my slides very shortly. If you were an attendee there should be a video at some point, although I didn’t see any cameras so maybe it’s just a screen cast or something. It was my first full session at a big conference, and definitely an item ticked on my bucket list. I’m mega grateful to conference organiser John Davey for putting me up there, and Pokemon Trainer Seb-Lee Delisle for being my hype-man for the last 2 years. Without Seb, probably nobody would know who I am. He’s also a bloody ruddy nice bloke.


As happens at every talk I give (will they never learn!), some people asked me afterwards if I would share the source code from my talk. The demos are built on my work-in-progress game engine, so I can’t share the source to the games without also including the game-engine, which for business reasons I am not able to do, although a big chunk of it is already open-sourced in my Gamepad library.

The funny thing about geeks is, even when I do a session about design – purely the creative decision making side of games – geeks still just want to look under the hood! The main feedback was that people wanted to know the maths for the car handling physics, so I’m going to turn that into a tutorial and post that here on my blog. Also, if you’re more into the wizard stuff, I have the full source for a different Zelda-style wizard game that I made a while ago, that I am going to give away here too.

Slightly weirder was my last minute addition to the “jam throwdown” on the terrifying main stage. I was only asked to do it the night before, and had planned to show my complete greatest hits from the last 11 years of my work. Not having a chance to rehearse, I didn’t know that this was actually impossible, so what the attendees got was about the first 5 years, which was loads of terrible, daft lo-fi experimental Flash stuff and a few games. It seemed like people got the joke, but I did have a small bout of paranoia that everyone hated me straight after. Do not underestimate the social paranoia appearing at conferences can give you! I have had some nice feedback about the slot on twitter since though, so I feel ok about it now. People were probably just being nice, but thank you, I appreciate it!


(photo Copyright All rights reserved by oyvindnordhagen)

Even though I’m just a geek talking about geeky stuff, it’s really hard not to get a bit of a rush from making a whole auditorium of people laugh or go “oooh”. I wonder whether this is why people like Hoss Gifford and Brendan Dawes pack their sessions with jokes? I don’t think I got into speaking as a back door into stand-up comedy, but to be honest I have no idea why I did want to get into it. Certainly a large part of me finds the whole experience completely harrowing. What is “speaking” or being a “speaker”? Why do it? What is it for? I have genuinely no idea.

That’s enough about me though, what about all the talented speakers? Well it was a slightly strange one for me. For one thing, since last time I have become even more focussed on game development, and there wasn’t much representation for gamedev, so there weren’t many sessions that apply directly to what I do day-to-day. From the queue outside my talk and Jon Howard’s (excellent) session, there’s obviously a lot of pent-up demand for it among attendees. Maybe next year John could try to book some Flash gaming luminaries like Dan Cook or Adam Atatomic? I’ll definitely suggest it to him.

I want to word this next bit very carefully so that I don’t offend any of the amazing speakers who I saw and spoke to during the conference, and who are all some of the most talented and inspirational people you will meet in this industry. Here goes then: basically what I’ve noticed is that not every speaker can inspire you as much the second and third time you see as they do the first time you see them. Even though everyone updates their material regularly with new work, nobody has an unlimited supply of mind-blowingness. Ideas that are revolutionary when you first see them get synthesised into the way you see the world. The same idea can never inspire you again in the same way it did the first time. This is no reflection on the talent of the speaker, it’s just the nature of ideas.

And this is why I loved the elevator pitch so much. Twenty speakers from completely different disciplines blasting you with as much information as they can get into a 3 minute slot. I know from experience that each 3 minute speech has many hours, if not days and even weeks of preparation go into it. This shows through massively and you get exposed to more new ideas in this session than any other. Someone tweeted that speakers collect elevator pitchers like Pokemon. I kind of played Pokemon Trainer a bit this year, encouraging Andreas, Jasper and Tom to do the pitch. This reflects very well on how I choose my friends, because my Pokemon were easily 3 of the best in the whole session.

Andreas presented his DDConsole aka DoomsdayConsole which is a runtime tracing/hacking/debugging/tweaking console for Flash, inspired by the ones you find in games like Quake. It’s completely open source and completely ace. Through some wicked 8-bit graphics and animation, Tom presented his awesome sound effects generator AS3sfxr with such style that he also managed to subconsciously teach you how to do the creative side of sound design.

Jasper showed us all why Unity3D is the crown prince of 3D game engines by building his slide-deck as an Incpetion/Matrix inspired fly-through of a city falling into place. Nobody loves Unity as much as this guy. He’s thinking about it most the time. He’s probably thinking about it right now. What he didn’t tell you during his slot was that he taught himself to model in Maya just to make his presentation. And you’d never have noticed it, because his models looked awesome. I could tell that Jasper enjoyed the experience because I spoke to him after and he had a crazy look in his eye like someone who had just discovered crack. Anyways, if you went to the conference, please vote for these guys on your feedback form, they’re ace.


The stand-out session of the conference had to be Seb’s “What the flux?” There’s been a lot of mud thrown back and forth this year between Flash developers, HTML5/web standards advocates, and of course Apple, and Seb has spent a lot of time trying out these various competing technologies. He presented a some home truths that I don’t think everyone was ready to hear, but presented it a way that was optimistic, pragmatic and tried to build bridges. He had video interviews with some smart people from both camps, which he cut in with some political slogans, a game show skit and some jokes. I don’t actually agree with him that JavaScript and HTML5 are anywhere near ready to move into the immersive/experiential/flashy uses of Flash, but on everything else he was about right. He did point out that Flash is still the mofo daddy for web games.

Grant Skinner showed some cool physical device experiments like using Android phones as controllers for 8 player Asteroids and even as accelerator pedals for Scalextric. Also there was some marital aid hacking which raised a few eyebrows. In Grant’s session I began experimenting with starting rounds of applause, my first attempt failing and making it seem as if I was slow clapping, which was quite an amusing little moment that he dealt with like the pro he is. After that the audience really got into it, and through my further efforts I managed to increase the numbers of rounds of applause in all sessions I went to by at least a factor of 2 for the rest of the day. This is great for the atmosphere of the conference. If everyone is showing appreciation of a good speaker it actually increases the speaker’s confidence and makes for a better session. Towards the end of the conference I noticed an annoying trend that people were only clapping videos and not any other type of work that was shown. This is really silly and completely unfair on speakers who do different kinds of work, e.g. INTERACTIVE STUFF.

Other highlights were surrealist animator Cyriak Harris, design legend Stefan Sagmeister and designer/director Nando Costa who made this year’s amazing title sequence, which is frankly the sexiest form in which my name has ever been written. Watch it and see why. Nando showed some wicked film work he’d done with Modest Mouse (who I love) as well as other portfolio stuff. I chatted with Nando later about life in Portland and he’s a thoroughly nice bloke. I am now 1 degree of Kevin Bacon away from Modest Mouse which is a nice thought, although completely pointless.

I am completely exhausted now, so I’m going to get back to normality for the rest of the year, and take my Zero to Game Designer in 60 Minutes talk on the road in the new year. Thanks so much to everyone I met for being so supportive!

Tuesday, 21 September 2010

No Sleep Till Brighton


Ok, so. It's the week before Flash on the Beach 2010, which is my first full speaking engagement at a major conference, and I have a nice mix of excitement and dread. My talk, "Zero to Game Designer in 60 Minutes" is all written, and I've got 8 specially created interactive examples demonstrating different gameplay mechanics. Each demo has an avatar you can control, and a load of sliders and switches you can use to change variables and turn on and off different mechanics.

If you're coming along, and you bring your laptop, you can actually play along with the demos while I show them, which should make the session even more fun. And if you're not going, or you don't have a laptop, don't worry, because I'm going to put all the demos online from the minute my talk finishes.

See you in Brighton, or watch this space for the online release.

Tuesday, 14 September 2010

Thoughts on re-skinning games

I just received an email from a Flash developer who reads my blog and wanted some advice about creating a pinball game. He wrote that he doesn't have much experience making games, and he's been given a really tight deadline, so should he try and find an existing game to reskin, or should he develop the game from scratch? So reader, this is my advice:
  • Firstly, don't even think about grabbing a game from a portal and decompiling it. It's immoral and it's illegal.
  • One idea might be to go to http://www.flashgamelicense.com/ or https://www.mochimedia.com/ and search for pinball games. You can then contact the developers and ask them if they'd like to reskin their game for you or supply the source files so you can do it yourself. This option may actually work out much more profitable than developing the game yourself.
  • If you do a google search for "flash game source code" you will find there are many companies selling source code for Flash games, often at really low prices, and you may be able to find a pinball game somewhere in there.
  • Finally, if you do decide to code the game yourself, your best option might be to try http://www.box2dflash.org/ - this physics engine will handle all of the hard maths and physics you would need to do a pinball game - you would just need to learn the API and hook up the graphics.
Bye!



Flash on the Beach 2010 schedule picks

Everyone seems to be posting what they're looking forward to seeing, here's mine:

Monday:
  • KEYNOTE
  • GRANT SKINNER - ADHD FTW, LOL!!! (although would also have loved to see Conrad's Signals/Robotlegs talk)
  • ANDRE MICHELLE - PULSATILE CRACKLE
  • MARIO KLINGEMANN - SO LONG, AND THANKS FOR ALL THE FLASH (Mario's last conference session for a few years apparently)
  • HOSS GIFFORD - THINGS I HAVE LEARNED.
  • ROBERT HODGIN - PRACTICE MAKES PERFECT, SO WHAT ARE YOU PRACTICING?
  • STEFAN SAGMEISTER - DESIGN AND HAPPINESS

Tuesday:
  • THE ELEVATOR PITCH (I did it last year and it was loads of fun. This year look out for my buddies Jasper Stocker and Andreas Ronning)
  • JON HOWARD - WHERE IN THE WORLD? INTERCONTINENTAL BALLISTIC FLASH
  • JOA EBERT - 1 1 7 11 21
  • SEB LEE-DELISLE - WHAT THE FLUX!? (the only talk capable of sparking a Flame-war!)
  • JULIEN VALL√ČE - STORYTELLING, PLAYFULNESS AND EXPERIMENTATION
  • NANDO COSTA - THE OTHER SIDE
  • BRENDAN DAWES - MAKERS OF THINGS

Wednesday:
  • 6 OF THE BEST - 10 MINS EACH (although I'm probably going to have to duck out of the last couple so I can compose myself for my session)
  • IAIN LOBB - ZERO TO GAME DESIGNER IN 60 MINUTES (I better be there - I'm giving it! You'll notice that I've got the really small room, and I'm giving the only games session, so if you want to come you better run straight from the previous session without stopping for coffee)
  • RALPH HAUWERT - UNITZEROONE :: THE DISCONTINUITY (although Hugh Elliott is awesome and I'd have loved to see his thing)
  • CYRIAK HARRIS - ANIMATED MENTAL MALFUNCTIONS
  • JOSHUA HIRSCH - SUMMER FRIDAYS
  • JARED TARBELL - THE COMPUTATIONAL ARTIFACT
See you in Brighton!

Wednesday, 4 August 2010

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!

Monday, 26 July 2010

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.

Friday, 23 July 2010

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.




Wednesday, 21 July 2010

Goals, missions and quests

Games with little in the way of narrative tend to have quite abstract goals for the player to aim for. I've written before that "games are about the relationships between objects in space", and in a pure game like Tetris or Connect 4, the goal is simply to get some objects into a particular spatial relationship, for example a straight line. Most action/adventure games however, use three basic goals :
  • Kill enemies (like Space Invaders)
  • Collect items (like Pacman)
  • Reach Location (like Mario - although he also collects items and kills enemies)
Even a game like Gears of War is basically made up of just these goals - get to the extraction point while picking up weapons and ammo and killing locusts. But that's not what makes GoW exciting or fun - it's the obstacles that get in your way - environmental puzzles to solve, enemy behaviour to study and overcome, and the twitch skill you need to survive.

The problem with RPG quests, like you find in World of Warcraft, is that they often remove all the obstacles, puzzle solving and skill that GoW requires, so that all that's left is repetitive"grind" - fighting, collecting and trudging around, without any real thought going on. If the quest designer has the tools to make an interesting journey for the player, they can make something rewarding - if they are only able to define basic kill 10 rats scenarios, then the experience will be a chore.

Kill Enemies

It's worth noting before I get into this topic that "killing" doesn't really have to be as violent as it sounds. Killing an enemy can be as metaphorical as you want to make it. Maybe your enemies are only stunned, maybe you're freeing them from some king of mind control (wasn't Sonic like that?), maybe they're not really enemies at all but customers in your cafe that you need to serve. The gameplay effect is the same: you have tapped into the part of the human brain that has evolved to deal with understanding the behaviour of another sentient creature, in order to get what you want from it, be that to eat it, not be eaten by it, get it's money or win it's affections. In The Sims for example, aren't each character's enemies really their neighbours and housemates? They must be charmed and seduced in order for the character to get what they want from them. Failure to do so will send your character into a spiral of depression, which is ultimately the closest The Sims has to losing.

Each type of enemy should have a unique appearance, but most importantly should have a unique behaviour, way of moving and interacting. Encountering an enemy for the first time should be a mini-puzzle, where the player must figure out how they need to manipulate their avatar in order to avoid the enemy's attacks and hit with their own, even if that mental process happens deep in the reptile brain rather than through a concious decision. If the player has different types of weapons, abilities, special moves or unit types to control, then each should have a different effect and effectiveness against a particular enemy. Real time strategy games do this really well, where, for example, a commando can take out a person in a single shot, but is useless against vehicles, forcing the player to think strategically about which enemies to attack with which of their own units.

Collect Items

Collecting items can be for its own sake, or it can be because they confer some ability that is useful in achieving the player's other goals. A game like Farmville uses only this goal - the aim is to accumulate as many coins, crops and animals as possible. There are is no location to reach or enemies to kill or avoid along the way, and you are never in any peril. The only thing you can do wrong is to not login to the game to harvest your crops, but this doesn't require skill or strategy, only a tireless devotion to the game. This is how Farmville is so successful in attracting a non-gamer audience. The player is only rewarded and never punished, unless they decide they have something better to do.

In a game like Gears of War, the main purpose of items is to make the player more effective in killing enemies. A gun or ammo pack has no sense of worth, other than as a means of eviscerating the enemy, and a player will happily toss it aside when something else comes along. Now compare this to an RPG where a weapon also has a monetary value and might have been difficult to acquire, and you'll find that a weapon becomes much more a prized possession. RPG's are very materialistic in this regard - every item has a price and the player spends a lot of time studying and organising their "inventory" and shopping for new items. As in The Sims, there's a lot of playing dress-up/playing with dolls here, and this is something which actually appeals to boys as well as girl gamers.

Collecting items can also be used as a way to test the players skill at the game and knowledge of the levels, with items placed in hidden or hard to reach places. Even Gears of War has it's Cog Tags, which serve no purpose other than to demonstrate that a player has a trawled every virtual inch of the game, which brings me onto the next topic...

Reach Locations

Since the earliest recorded times, stories have used a journey structure, where the protagonist sets out to reach a particular place and has an adventure along the way. Humans evolved to be semi-nomadic, and even the biggest homebody has a wanderlust somewhere deep inside. We love to travel, or climb trees or see what's around the next corner, even if we have no need to. Ever since the technology has permitted games with a playing area larger than a single screen, videogames have used this urge. But we tend not to make it too easy for the player to go exploring. Aside from enemies in the player's way, there are also environmental obstacles. I personally get nothing out of having to perform a set of perfectly timed jumps on every screen, but there are also environmental puzzles to test the player's logical brain, as you see perfectly executed in games like Half Life 2 and Portal.

So that's my breakdown of what I see as the 3 main goals a player has in a typical videogame: kill enemies, collect items, reach locations. Or if you wanted to be really reductionist, you could say that the goal of games is to keep some objects far apart and some close together.

Go any thoughts on this? Post them in the comments.

Monday, 19 July 2010

Some thoughts on character design

Some random things I remember reading about character design, and some things that have worked for me. Thomas the Tank Engine breaks both my first two rules, so should be an example of the bad character design, but somehow kids love it!

  • a character should be recognisable from just their silhouette.
  • Each character in a group should have their own colour scheme.
  • Simply-drawn characters are easier for the player/viewer/reader to relate to, because they are less specifically one person, and more of a vessel for the player to project themselves onto.
  • For the same reason as above, characters shouldn't say much - that's the Gordon Freeman effect. Most game characters don't talk, and when they do talk, on spin-off cartoons etc (e.g. Sonic), it's annoying.
  • In games you can express a lot about the character from the way they move and interact with the environment.
  • For unique costumes, raid the history books for crazy armour, uniforms, hats and dresses, and adapt to fit your setting.
  • Don't use anything that is too reminiscent of another famous character, e.g. blue spiky hair, red overalls etc
  • If your game/whatever is very focussed on the main character, name it after that character, as this will avoid confusion later. For example, all the Indiana Jones movies are called, "Indiana Jones and the..." except the first one is just called "Raiders of the Lost Ark", which could be a bit confusing. This is also true of Rambo - the first movie was just called First Blood, but most people think it was called Rambo. Possibly the worst naming decision ever made was Nintendo making a series of games called Zelda where that wasn't even the name of the character. This has confused the hell out of kids for 2 decades now!

Thursday, 1 July 2010

Now I have a games portal too! (DullDudeGames.com)




Now I have a portal. There are a lot of Flash games portals out there. Maybe a million, maybe a billion; who can say? And does the world need another one? Probably not. So why have I made one? (OK, enough rhetorical questions now!)

In case you don't know, a summary of how the indie Flash games business works is this:

- Developer makes a game
- Developer licenses game to a primary sponsor and adds branding and links back to sponsor site within the game.
- Sponsor pays developer, and as long as developer didn't spend too long making the game, developer makes a profit.
- Sponsor sells advertising on their site. The advertising (hopefully) generates more revenue than the sponsor paid for the game, so they make a profit.

If you create a game, but don't have a sponsor, you have some surplus value, which is the traffic your game could generate, that doesn't go anywhere. So make your own portal and put some ads on it! Which is what I've done, because I didn't manage to get a sponsor for a little game I knocked up to coincide with the world cup called World Class Keep Ups. Of course, business wise, there's a strong possibility I'm just chasing the loss from World Class Keep Ups and will never get back the (very modest) time investment I've put into setting up a portal.

But there's more to life (and games) than money, which is why I've taken the opportunity to put right some things I think are wrong with many existing portals...

- Too many games. Have you ever heard that truism that if you give someone a choice of 30 flavours of jam they'll end up not buying any of them? The cognitive stress of weighing up all the options actually puts them off buying anything. I think this is true of portals as well. If you have a screen with 100 games in it, how are you supposed to know which one you want?

- Organising games by genre. Personally, I don't like sports games, or arcade games, or platform games, or any other arbitrary category of games. I just like good games, I don't care how you categorise them! I'm not really into sports but I loved NBA Jam, I'm not especially into gory violence but I love Gears of War. I honestly don't believe anyone starts a visit to a games portal by thinking "hmmm... I'm in the mood for a driving game!". I think they just want to play the best game that's out there.

- Tiny thumbnails. Average file sizes for Flash games are at least 2mb these days, even some pre-game/banner adds are nearly that big if they include video. So why do games portals give you a tiny 100x100 pixel thumbnail for each game? This is too small to actually fit a screenshot on, so designers end up just using a logo or headshot of the main character, which doesn't actually tell the gamer much about the game. So I've allowed enough space on my trading-card shaped thumbnail to fit a decent gameplay screenshot.


- Rubbish games. I know as well as anyone that making fun games is very hit and miss. Some games are great on paper, but just don't work when you come to play them. Portals that rely on users to filter and rate games to determine which game are shown, by definition show a lot of duff games to players. This is fine if you have a lot of users, like Kongregate, but doesn't work if you only have a small amount of traffic - it just looks like you'll shovel any s*** on there. Which is why I have hand-picked only games that I enjoyed the hell out of.

- Games get lost on the page. Many portals cram a lot of junk onto a busy layout, meaning the poor games are pretty lost within the page. I've stripped it down to just the essentials: my logo, game title, ad units, game, instructions, more games . I've made everything nice and big and not worried about "the fold" as I trust users to scroll. And best of all my site can handle a custom background and colour scheme for each game, meaning each game gets a full page "takeover" and the whole sites transforms to be sympathetic to the look of the game.

- Burying games too deep. Some sites are hard to navigate because it can take 4 or more clicks to find the game you are looking for. My site has a completely flat structure - there's not even a browse games page or even a homepage! Each page contains thumbnails to the full roster of games, which is never going to get so big that I can't fit it all on one page (after all I have to play and love any game that gets on there).

So there you have it. Enjoy DullDudeGames.com and maybe have a think about what you think a games portal should be?

Tuesday, 29 June 2010

Unity Game Development Essentials - Book Review


The publishers of Unity Game Development Essentials, Packt, were kind enough to send me a review copy of the book at the end of last year, but I have been so stupidly busy I didn't have much time to read the book let alone post my review. I had originally planned to only read the book while sat in front of Unity so that I could work along with the tutorials, but again time got me so I ended up just reading it on the train. As it turned out this didn't actually cause any problems, and I managed to turn an unproductive commute into some very productive learning time.

The book is basically one long tutorial that shows you how to make a tropical island, set up a first-person camera to walk around it, and create some interaction with the environment, such as collecting objects, opening doors and (don't ask me why) throwing coconuts. Between this book, Unity3d.com's tropical paradise demo and Offroad Velociraptor Safari, you will be forgiven for thinking Unity can only make games set on tropical islands. I assure you this is not true.

Going through these kinds of tutorials is not how I normally learn a technology. My normal approach is to just fire up the editor and start hacking code until something moves on the screen - as I did with Unity last year. However, I have to say that for Unity, which is a very unique, graphical interface driven technology, the approach of going through tutorials is actually better. I learned many techniques from the book (e.g. using the terrain editor, setting up the skybox) that aren't immediately obvious from just poking around the IDE.

The book is meant for a wide audience, including designers, and the code is quite basic, and not necessarily the most "correct" way of working if you're coming from the world of design patterns, MVC frameworks etc. However, I don't see this as an issue, as if you know a better way of doing things it will be trivial for you to refactor the code to meet your needs. The caveat, however, is that the code is all JavaScript, and many Flash guys will be more inclined to take the C# route, despite the obvious similarities between AS3 and Unity's implementation of JavaScript.

The book's main drawback is that at the end of it you haven't really made a "game" in the sense that I understand it. You've made a kind of interactive environment with some coconut throwing. The book's main benefit, however, is that it gives you a nice introduction to all the facets of Unity, from terrain, cameras, physics and prefabs to adding a user interface and menu. Many parts of the book are written just for people coming from Flash, and if that's you, you will definitely be able to go off and make your first game after reading it. Overall, if you're just getting into Unity I think this is a great place to start.

Thursday, 20 May 2010

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.


Thursday, 13 May 2010

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!