Flash Game Dev Tips Category

  • Flash Game Dev Tip #10 – Flixels Internal Structure and Performance Tips

    Tip #10 – Flixels Internal Structure and Performance Tips

    If you’ve ever wondered just what Flixel does when it starts-up or runs its main loop, then wonder no more 🙂 Here’s the full gory details, with some take-away performance tips at the end.

    The Instantiation Process

    All games in Flixel extend the FlxGame class, which in turn extends Sprite. When the game is created the following process happens, in the following order:

    1. It hides the system mouse cursor
    2. Calls FlxG.init which clears the bitmap cache, creates a new Sprite (flashGfxSprite) and creates an empty cameras Array
    3. Sets the internal game frame rate
    4. Sets the Flash Player frame rate
    5. Adds an ENTER_FRAME Event Listener which triggers FlxGame.create

    Frame rates

    Flixel 2.5 uses a Deterministic Delta Timer to handle steps within the framework. A step (as you’ll see later) is processed in the main loop, and is when Flixel performs all of the collision, separation and movement calculations. This is not the same thing as when it renders the game. When you create your game you have to tell FlxGame what game frame rate and Flash Player frame rates you want. From these two values it does the following:
    • Sets the step to be 1000 / Game Frame Rate. So a rate of 30 updates per second would equal a step of 33.
    • Sets the Maximum Accumulation (maxAcc) value to 2000 / Flash Player Frame Rate (fps) – 1.
    • So an fps rate of 30 would equal a maxAcc of 66. The maxAcc can never be less than step.

    FlxGame.create

    This function is only run once. It’s main responsibilities are creating the various event listeners that Flixel uses:

    1. It sits in a loop until it has access to root. Once it does the ENTER_FRAME event listener (created above) is removed
    2. The Stage scale mode is set to NO_SCALE, alignment to TOP_LEFT and the Flash Frame Rate is set (once again!)
    3. Mouse Up, Down and Mouse Wheel listeners are started
    4. Keyboard Up and Down listeners are started
    5. A new empty sprite called _mouse is created an added to the display list (it will contain the bitmap mouse cursor later)
    6. The FlxDebugger is created and added to the display list
    7. Creates the Sound Tray
    8. Creates the Lost Focus Screen (the large play arrow with the Flixel icon top left) and starts Event.ACTIVATE and DEACTIVATE listeners
    9. Adds an ENTER_FRAME for FlxG.onEnterFrame

    Processing ends here until the next Enter Frame event fires. At that point we’re out of the creation phase and into the main loop.

    You may feel like doing this to your computer by the end :)

    The Main Loop – FlxGame.onEnterFrame

    The guts of Flixel. Everything happens from here, one way or another.

    1. It starts by setting a var called mark to equal getTimer. The elapsedMS value is then calculated from this. That is the number of milliseconds that have elapsed since the last enter frame event occurred.
    2. The Sound Tray is updated
    3. If the SWF file has focus then it will process the core of this function, otherwise it bails out.

    Core Loop Actions

    1. If the FlxDebugger has been created and is currently paused then it checks to see if a debug step was requested. If it was it runs step once.
    2. If the FlxDebugger is not paused, then the game is running normally and as such it will work out the Accumulator value. It does this by adding the elapsedMS total to it. If it’s higher than the maxAccumulator set in the creation phase then it’s set to equal maxAccumulator.
    3. Something very important happens here. If Accumulator is >= step then it calls the step function. It then reduces the value of Accumulator by step and checks again. It will literally loop this until the accumulator is no longer large enough to warrant running another step call. You’ll notice that when your game first starts up, due to default values step is likely to be called several times. I’ve seen the accumulator go 150, 117, 84, 51, 18 – at which point it stops. So it’ll literally run step 5 times. Typically in a normal game this isn’t the case. As the values balance out step is usually only called once or twice per loop. On some occasions, usually after some heavy garbage collection, step fails to be called at all. This is quite undesirable imho, but is how it works.

    The Step

    So what happens when Step is called? First it checks to see if there is a Reset Request pending. A Reset Request would occur if you had asked Flixel to change to a new FlxState. It will also always happen the very first time your game is started.

    1. It creates a new instance of the given FlxState
    2. Resets the Replay Timer
    3. Calls FlxG.reset

    FlxG.reset

    1. Clears the Bitmap Cache (again :))
    2. Resets Input
    3. Destroys all sounds
    4. Resets various internal arrays and variables to zero
    5. Sets the TimeScale to 1.0
    6. Seeds the random number generator
    7. Sets the World Bounds to -10, -10, Width + 20, Height + 20
    8. Sets World Divisions to 6
    9. Creates the DebugPathDisplay Plugin

    Read More

  • Flash Game Dev Tip #9 – Dealing with a lack of motivation to finish your game

    Tip #9 – Dealing with a lack of motivation to finish your game

    You are not alone

    Everyone suffers from this problem at one point or another: You simply can’t face the thought of working on your game. This is especially hard when making the game in your “free time”. It’s all too easy to think “what the hell” and double-click that Team Fortress icon instead of FlashDevelop. And even days when your head is saying “let’s code!” all that motivation can vanish the moment you open the source and realise that its been so long since you were last here it’s like staring at a foreign language, or a giant brick wall and you have no idea what to start first.

    There is no “single solution” to fix this. It’s extremely personal. Your reasons for not wanting, or being able to code will be as varied as the number of people reading this. But as I said at the start you are not alone – so I posed the question of how to deal with it to 13 fellow game developers and collated their replies. Hopefully somewhere in these insights you’ll find a technique or suggestion that helps you out. And if you have one that you personally use, not already mentioned, please post it into the comments.

    I’ll kick things off …

    Richard Davey / Photon Storm

    http://www.photonstorm.com

    I’ve come to realise that I’ve a game development mana reserve. When I start work on a game, my mana reserve is full. But as coding begins this reserve drops faster and faster. Sometimes if I hit a particularly troublesome spot in a game it can be enough to utterly wipe-out what reserves I had left, derailing the project entirely. But there are also the “wins”. Getting a significant part of the game finished, or adding something really cool. That helps re-fill my mana reserves and keeps motivation high. It’s a constant battle. To get the game finished before enthusiasm is depleted entirely, yet to have enough wins on-route that they keep things in balance.

    The “wins” however cannot be artificially placed into the project. They have to be unexpected and grow almost organically as a result of  working on the game. Equally the hits to my morale are never expected either. I never start coding expecting to stump my toe on a  bug from hell, but it happens.

    There are two issues here:

    1) Having the motivation to continue working on a game

    I think like a lot of people I’m most excited about a game during the very early stages of it. The feeling of bringing something to life, of getting the idea out of your head and into code – that’s a real achievement in and of itself. I enjoy the task of getting a working prototype up and running, often with really crappy code driving it. The thing to do at this stage is to try and work out for yourself if you should stop right now, and not even attempt to carry on.

    Use those prototypes

    There is nothing wrong in building a prototype and just leaving it at that. Of course if you’re in this for the money it’s not going to get you rich, but if like me you do this for fun then you shouldn’t feel any sense of “guilt” for having made just a prototype. If by this point you recognise that your enthusiasm is on the wane already then don’t just file it away for another day, thinking you’ll come back to finish it later on. Because almost certainly it will never happen. If you don’t have the enthusiasm or excitement at the end of this stage to take the game further, then you never will.

    Don’t waste it though. Think about how what you’ve made could be useful to others. Perhaps it’d serve as an interesting “I made this little demo” post for your blog or a forum. Or maybe it could be turned into a tutorial for a development site with little modification. You may be surprised at the response. I’ve had people see “demos” of work who suggested just one change, that radically altered the course of the game, resulting in it being finished and released. As I mentioned at the start, “mana refills” can come from anywhere, sometimes the most unexpected of places.

    Do something other than making games

    Making complete games is hard, there’s no doubting this. Even the most simple of games still require quite tedious boot strapping to make them suitable for release. But that “rush” and feeling of sheer joy you get when you finally publish doesn’t always have to come from making a game. As readers of my blog will know I work on a lot of game development projects such as my Flixel Power Tools or tutorials. I do this because I enjoy writing, but also because I remember what it was like being fresh to development – how I was a sponge, soaking up every last piece of information I could get my hands on.

    There is a real thrill in authoring this type of content too, and publishing it. So you don’t feel like making a whole game? No problem – could you make a demo that showcased how to make a sprite jump from platform to platform? The scale is significantly smaller, but the end result could be extremely useful to your fellow developers. And their feedback can be enough to spur you on during the more laborious development work you need to do.

    Of course the downside of all this writing is that it takes your time away from making actual games, as Ilija will attest to 🙂

    Public Beta Tests

    We ran a public beta test of a game called Kingdums. We just put a build of the game onto a web page with a big feedback form below it, and shouted the URL onto twitter. It was live for a week. The feedback we got was fantastic, because it under-lined a significant flaw in the game (that was in the back of our minds anyway, but made it prominent) and reaffirmed that actually, this flaw aside, people really enjoyed playing it. Other developers use public beta tests for similar reasons – lots do it to find out if their games have bugs they’ve missed, but it doesn’t just have to be about that. Sometimes you’ll get suggestions that highlight issues you didn’t see, and sometimes it’s just a good morale boost.

    It’s not just code that can be tested – you could post-up screen shots, character bios, even basic story arcs. All things that feed back into the game overall.

    Enforced Time Constraints

    Some people don’t understand the point of making a game in a limited period of time. Others relish the challenge. Personally I fall somewhere in the middle. I haven’t yet had a chance to take part in something like Ludum Dare, because I have a family life that stops things like that happening over weekends. But the times that I have made a game in a limited period of time (we’ve done it 3 times now) it has always worked for the better. Todo lists get cut down dramatically. Only the essential game aspects are given attention, and the time limitation really does focus your mind. Try it, it may appeal to you.

    Using a To-Do List

    You’ll see this suggestion raised time and again by the other devs below. Ilija and I use the free software Wunderlist. I like the fact I can add items from my iPhone or PC and have it all sync-up properly. We don’t have lists for prototypes, only for games deep in development. I find it pointless starting a list with “make an enemy manager”, that feels too early-on in the process for us.

    2) Dealing with “getting stuck” while coding

    This is the easiest to solve. If you have a coding problem, then you ask for help. If you don’t work in an environment where you can ask fellow coders for suggestions, then there are hundreds of really great game dev communities online. And you should join one and really participate with it. Help out other people suffering problems you may already solved, and post your problems up there also. More often than not someone will help, or at least direct you onto the right path that leads to solving the problem anyway. If you can’t solve the issue within a couple hours of trying, and can’t think of another way to approach it, then you need a bring a second brain into the equation. The longer you delay in asking for help, the more chance you have of never finishing.

    Don’t feel guilty

    You’re only human. Human’s need a fine balance between work, rest and play. And developers are terrible at balancing those three elements. There’s a famous producer graph showing “Price – Speed – Quality”, with the mantra that you can only ever have 2 of those 3 things. So “Speed + Quality comes at the expensive of Price”, or “Low Price + Speed means low Quality”.

    I feel that developers do the same with “Coding – Resting – Playing”. By “Playing” I mean taking time out from coding: watching a movie, spending time with your significant other, reading a book, playing Xbox, etc. Too much coding but the right amount of sleep usually means you give-up your “play” time. If you’re burning the candle at both ends, holding down an intensive day job and then coding all night, your Rest and Play can be sacrificed. If when you sit at your computer you find the code just isn’t flowing then stop. Don’t battle it, don’t trudge through. Just stop and do something else entirely (ideally non-computer based). Then try again the next day. If you’ve been working like mad all week, getting a few hours sleep a night, then pay off that sleep debt.

    Development is a roller-coaster of highs and lows. If you recognise you’re on a coding streak then enjoy it and use it to your advantage, but when it ends (and it will end) switch track quickly and work on something else. Then switch back again. The quicker you learn to recognise your “moods” the more useful you can make them. I’m not perfect at this yet, not by a long shot. I still have lots of “unfinished” games, indeed the artwork I used to illustrate my text above is all taken from games I’ve not yet finished, and there are plenty more. But I never sit idle. I do at least work and release. If I’m not making a game, I’ll write, and if I’m not writing I’ll help out in a forum. If I’m not in there maybe I’ll be playing a little Counter Strike. The point is that I feel I do balance them well, one doesn’t over-power the other. I just wish I had more hours in the day 🙂

    That’s me done with, now onto 13 other developers for their views on this subject …

    Read More

  • Flash Game Dev Tip #8 – Building a Shoot-em-up Part 3 – Return Fire

    Tip #8 – Flixel – Building a Shoot-em-up, Part 3 – Return Fire

    This tip follows-on from Tip #4, where we added enemies and explosions into our game. But it was a little one-sided. This time the enemy are going to shoot back. And you’ll feel it, by way of a health bar and set of lives in our new HUD. Finally we’ll drop in the scrolling tile-map background and simple menu / game-over states. By the end it will look like this:

    Note: I’ve embedded the game at the bottom of the tip.

    Return Fire

    Last time we added the Enemy Manager, which spawned a regular supply of enemies at us. Each enemy had a launch function which set it moving. Let’s add the ability to fire to that:

    //	Will they shoot at the player? 70% chance of doing so
    if (FlxMath.chanceRoll(70))
    {
    	willFire = true;
    	fireTime = new FlxDelay(1000 + int(Math.random() * 500));
    	fireTime.start();
    }
    

    This uses a new FlxMath function chanceRoll. The enemy has a 70% chance of firing at you. If this happens we create a new FlxDelay Timer of 1 second + up to an extra 0.5 second, and start it running.

    Then in the Enemy update function we check that timer:

    if (willFire && fireTime.hasExpired)
    {
    	Registry.enemyBullets.fire(x, y);
    	willFire = false;
    }
    

    As you can see, this is calling the fire function in our Enemy Bullet Manager, passing in the x/y coordinates of the Enemy, which launches a bullet from the bullet pool:

    public function fire(bx:int, by:int):void
    {
    	x = bx;
    	y = by;
    
    	FlxVelocity.moveTowardsObject(this, Registry.player, speed);
    
    	exists = true;
    }
    

    FlxVelocity tells the bullet (this) to move towards the player at the value of speed (which in our case is 240 pixels per second).

    Read More

  • Flash Game Dev Tip #7 – Introducing the Flixel Power Tools

    Tip #7 – Introducing the Flixel Power Tools

    For the latest Flixel Power Tools please go here

    Update May 11th 2011

    Since writing this tip the Flixel Power Tools have grown from strength to strength having all been updated to use the new Flixel 2.5 plugin system. Plus there are loads of new classes, a new test system and a comprehensive Getting Started Guide. I will leave this Tip here as it applies to Flixel v2.43 but if you are coming to this fresh then please…

    For the latest Flixel Power Tools please go here

    — End of Update

    Quite frankly flixel is awesome. It allows me to rapidly build games. The sort of games I like playing (and therefore making!) While it does a lot for you it is lacking in a few key areas. After all it’s just a framework, and frameworks are meant to be built-upon.

    That is where the Flixel Power Tools come in! At the time of writing there are 13 new classes, all neatly arranged in a single package, that push flixel just that little bit further. There is also a test suite which include 16 easy-to-follow examples of the power tools in action, with a funky visual menu system and a way to actually see what they do. I always find it easier to learn by looking and then checking out the code!

    The majority of these tools work without even touching the core flixel code-base. Although there are some that do require it, so with that in mind I’ve provided a fully Patched version of flixel 2.43. But if you’ve got your own build there are instructions on manually patching at the top of each class that needs it, and work-arounds should you not want to touch anything at all!

    I will continue to expand the library of tools and the test suite. And of course keep them in-line with the way in which the flixel codebase is changing at the moment. For now here is a quick overview of what each new class offers:

    FlxBitmapFont

    Allows you to use bitmap fonts in your games very easily. It’s extremely fast. Fast-enough for real-time updates, or a GUI or HUD display. The rendered text is just a normal FlxSprite, so you can do with it whatever you like. Extensive character-set handling options and fully documented.

    
    font = new FlxBitmapFont(bluepinkFontPNG, 32, 32, FlxBitmapFont.TEXT_SET2, 10);
    font.setText("easy :)", true, 0, 8, FlxBitmapFont.ALIGN_CENTER);
    

    FlxButtonPlus

    Takes the FlxButton class you already know, and then pimps it out some! You can specify parameters for the callback, the button width, height and text in the constructor. Change the button text dynamically. Set hover-over and hover-out callbacks. And the default button style is now a nice gradient filled affair (which you can control the gradient colours of yourself). Or just use loadGraphic to replace it.

    
    playback = new FlxButtonPlus(32, 32, toggleMusic, null, "Play Music");
    

    FlxCollision

    Collision in flixel is handled with bounding boxes. Which is basically two rectangles colliding, and if they intersect you get a collision back. This class takes it the necessary step further and adds pixel perfect collision testing. Only the intersecting area is tested for speed. And you have control over the alpha tolerance level (so you can exclude pixels with an alpha level less than what you need). It also works with scaled, rotated or animated FlxSprites! and is perfectly fast enough to use in real-time.

    
    if (FlxCollision.pixelPerfectCheck(player, spikes))
    {
        // Player really did hit those spikes!
    }
    

    FlxColor

    A very comprehensive class for serious colour manipulation! As well as being able to rip-apart and put back together colour values across all kinds of ranges (ARGB, 24/32 bit, to/from Hex, etc) it also has support for colour interpolation; HSV colour wheel generation; random colours and advanced colour effects. Including: getting a complement harmony colour, analogous harmony, split complement harmony, triadic harmony and RGB to HSV and HSV to RGB conversion.

    
    FlxColor.getRandomColor(20);
    FlxColor.getComplementHarmony(0xff00ff00);
    

    FlxDelay

    A useful timer that can be used to trigger events after certain amounts of time are up. Uses getTimer so is low on resources and avoids using Flash timer events. Also takes into consideration the Pause state of your game. If your game pauses, when it starts again the timer notices and adjusts the expires time accordingly.

    
    timer = new FlxDelay(2000);
    timer.start();
    ...
    if (timer.hasExpired)
    {
        ...
    }
    

    FlxDisplay

    A work-in-progress class. At the moment contains one function: screenCenter, which takes an FlxSprite and then centers it on the x or y axis (or both).

    FlxFlod

    This provides an interface between Christian Cortis excelled Flod replay library and flixel. Flod allows you to play MOD music in your games. The MOD format was made popular on the Amiga via SoundTracker, ProTracker, etc. Flod provides the most accurate replay of the MOD format at present (beating most desktop players). This class provides for a very easy interface to it.

    Also hooks properly into the flixel sound system. So if you change the volume, or mute or pause your game, FlxFlod will re-act properly.

    
    FlxFlod.playMod(musicMOD);
    

    FlxGradient

    Gradients are a staple of most retro games, usually used for pretty sky-backdrops or to fill in game objects or text panels. This class provides an extremely easy way to create those. It can generate an FlxSprite filled with the gradient, or overlay a gradient onto an existing FlxSprite (or portion of it). It can also generate an Array full of gradient values for use outside the class. Just give it an array of colour values, and it will do the rest. Gradients can also be “chunked”, making them less smooth (and more retro!) and rotated to any angle.

    
    var gradient1:FlxSprite = FlxGradient.createGradientFlxSprite(32, 32, [0xFF0000, 0xFF8000, 0xFFFF00], 2 );
    

    FlxGridOverlay

    I use grids a lot in my games, usually for aligning on-screen elements or sprites. This handy class will generate an FlxSprite filled with a grid of your dimensions and colours. The grid can be in a checkerboard style, or vertical stripes, and it can also be overlaid on-top of an existing FlxSprite (if you set the alpha channel on the colours you can build-up some really nice effects with just one line of code!) The background of the Test Suite was created with this class.

    
    FlxGridOverlay.overlay(background, 16, 16, 320, 240, false, true, 0x44e7e6e6, 0x44d9d5d5);
    

    FlxMath

    Like it or not, math is fundamental to game progaming! This class provides some new or just faster math routines, which a lot of the other classes in the package rely on. Things like radian/degree conversion, vector lengths, dot products, random numbers between ranges, random signs, value wrapping and a really fast sin/cos table generator.

    
    // Gets a random number between 0 and 10 but excludes numbers 4 and 5 from the possible results
    FlxMath.rand(0, 10, [ 4, 5 ]);
    

    FlxVelocity

    A class to help with setting and using the velocity of FlxSprites. With this you can move one sprite towards another, move a sprite towards the mouse, get distances between sprites / mouse and get angles between sprites and the mouse.

    It doesn’t sound very exciting (and it’s not to look at) but they can start to save you real time, and keep your code tidy and clean.

    
    // Move the blue ball towards green at a speed of 180 pixels per second
    FlxVelocity.moveTowardsObject(blue, green, 180);
    

    Classes still in development

    To be fair most of the classes are still being built! But these are 3 experimental ones in the library today: FlxMotion (will be used to control sprite motion such as bouncing, wobbling, etc), FlxPlama (a nice plasma colour effect) and FlxStarfield (3D and 2D starfield generator)

    Keep your eye on my blog and the svn commits for updates!

    Download

    The Flixel Power Tools are part of the Flash Game Dev Tips Google Code Project.

    You can download a zip file containing the tools, a patched version of flixel and the full test suite. Or you can checkout the repository from Google Code svn, and get exactly the same things, but far more up-to-date! As I’ll be working on this constantly. When I hit a major new version I’ll re-build the zip, but svn will always be bleeding-edge.

    Any questions about any of the tools? Ask me in the comments, or more usefully on the flixel forums.

    Update May 11th 2011 – For the latest Flixel Power Tools please go here

  • Flash Game Dev Tip #6 – Setting-up FlashDevelop and Flixel for the first time

    Tip #6 – Setting-up FlashDevelop and Flixel for the first time

    Last updated April 14th 2011 for FlashDevelop version: 3.3.4 and Flixel version: 2.5

    Hello World

    The popularity of Flixel attracts a lot of new developers. Often they are coming into it not from Flash, but from other languages and game making tools. There’s nothing wrong with this, but it’s all too easy to fall at the first hurdle: simply getting a clean working development environment set-up. One which you can then hit “compile” and see the all-magic “Hello World” appear, rather than a blank white window or an error message.

    There are lots of tutorials on setting-up FlashDevelop (see “Further Reading” for some), and a few on getting started with Flixel. But they are mostly out of date, and none of them marry the two things together. So I hope to address that in this tip. I’ll keep this tip updated as major new versions of FlashDevelop and Flixel are released.

    OS X dudes, take a different path

    First things first. You need to be using Windows. FlashDevelop IS coming for OS X soon. You can also run it under Parallels. And there are builds in development that you can download from the forum, but I’m not covering it here. Sorry if that excludes you. You’re welcome to come back and join us at the point where we integrate Flixel, as that will still be relevant to you.

    Windows people, let’s continue …

    The Development Process

    It’s important you understand what each part of your development environment does. It’s easy to get mixed-up with terminology, and not really knowing where in the chain a certain piece fits. The following diagram shows the build process:

    FlashDevelop is our editor, our IDE. It’s where you’ll type in all the code, and spend the majority of your time.

    When it comes time to test your code, FlashDevelop will run a program called mxmlc.exe which is part of the Flex SDK. It’s the job of this program to grab everything it needs, and fire it off to the compiler. The main compiler is written in Java, hence the requirement for Java 1.6 to be installed on your PC.

    At this point it’s very easy to get confused by the word “Flex” or even the involvement of Java. Traditionally Flex has been associated with Flex Builder, the Adobe application used for creating mostly dull and dry… sorry, for creating rich internet applications. Flex Builder uses MXML files to control UI layout amongst other things. Adobe since renamed it to FlashBuilder (I guess they get a kick out of confusing people). But you don’t need to care about this. All you need to know is that the Flex SDK contains the compiler, and that is what FlashDevelop uses. As for the presence of Java in this equation: the compiler is written in Java. But it doesn’t create java apps.

    What the compiler does is to take your Flixel / ActionScript 3 source code and process it.

    Providing there were no errors, the compiler will have turned your code into machine code, and output a SWF file.

    SWF files need to be loaded into Flash Player to be viewed. Most people are familiar with experiencing flash within their web browser, but you can (and will!) also download a stand-alone Flash Player to run SWF files from Windows, without needing a browser.

    Once your SWF is loaded into Flash Player, your game will begin!

    This whole process is repeated over and over during development. So let’s create this environment locally, and put together a set of flixel template files that will allow you to roll-out future projects quickly and easily.

    Read More