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:

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:

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.
  • 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 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.
  • 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
    //added to enemies vector
  • 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.
  • 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.

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 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! (

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 and maybe have a think about what you think a games portal should be?