Skip to content
Jun 25 11

Effortless Animations in Flash

by pixelpracht

You want to display an Animation in Flash. The animation consists of a number of frames, each is saved as a small image somewhere on your HD. You wonder: What is the best way to do it?

If this scenario applies to you, here is one possible answer that does not require the Flash IDE or any full blown framework. It involves a free tool and a couple of small classes (also free) that should be easy to integrate with your project.

Step 1: Create an Image Atlas out of the individual images.

What is an Image Atlas? A big image containing many small ones side by side. Also known as Texture Atlas or Sprite Sheet.

Why do we want one? Because it’s easier to embedd one image file than many. :) It’s also reducing the size of the SWF because it compresses better then individual images. We’ll use a tool called Texture Atlas Generator to create our image atlas.

Create an Image Atlas

  • Check “PNG” so an image atlas is generated.
  • Check “Pack Transparent”. This will pack the images as small as possible by removing empty pixels. The 17 original images have a resolution of 128 x 64 each. The image atlas has a resolution of 400 x 182. So the same animation takes up roughly half the amount of pixels.
  • Check “TXA” to generate another file that stores meta information e.g. what frame went where in the image atlas.
  • All other options can be un-checked.

If everything works you end up with 2 new files: A TXA file and a PNG image atlas that should look roughly like this:

Step 2: Embedd the image atlas and the meta data in your Flash.

As described in my other blog post you can embed all kind of data in a SWF.

[Embed(source = "../Resources/MoikSlashAni.txa", mimeType="application/octet-stream")]
private static var animationTxaResource:Class;
[Embed(source="../Resources/MoikSlashAni.png")]
public static var animationPngResource:Class;

Step 3: Use the ImageAtlas and AnimatedBitmap class to display the embedded animation.

In the Code Sample you’ll find a couple of classes from my library of custom code. Feel free to use them for your own projects. In this tutorial we’ll use the ImageAtlas class to unpack the individual frames from the image atlas and the AnimatedBitmap class (that behaves just like a normal Bitmap class with some extra functionality) that we will add to the stage to display the animation.

//unpack the embedded resources
var imageData:BitmapData = (new animPngResource as Bitmap).bitmapData;
var metaData:ByteArray = new animTxaResource;
//create an image Atlas storing our animation
var imageAtlas:ImageAtlas = new ImageAtlas(imageData, metaData);
//create an animated bitmap...
var animation:AnimatedBitmap = new AnimatedBitmap(imageAtlas);
//...make it play a sequence of frames...
animation.assignFramesByName("MoikSlashAni_0000", 16);
animation.play();
//and add it to the stage
stage.addChild(animation);

It’s as easy as that! :)

Sorry, either Adobe flash is not installed or you do not have it enabled

Download the sample project here: ImageAtlasTutorial

Step 4: Make it your own.

You probably want to have a look in the source code (to learn what AnimatedBitmap can do) and wrap the functionality with your own code. The AnimatedBitmap has a couple of functions that make it flexible to use.

  • You can toggle wheter you want the animation to loop.
  • You can set the current frame yourself or let it update automatically (by calling the play method).
  • You can reassign new frames so you could store a lot of different animations in the same image atlas. Running, Slash, Jump and so on. So one image atlas and one animated bitmap could be enough to display a full character. You just have to change the sequence of frames you want currently played e.g. assignFramesByName("jump001", 14) to play 14 frames of jumping.
  • You can pass a callback function as a parameter to the play that is called when the last frame is reached (and the animation isn’t looping) to play a follow up animtion.

I hope this tutorial has given you something to get started with! Feel free to post further questions in the comments. :)

Copyright Notice: The sprite I used in the demonstration is public domain and consider the code used in the sample as released under the MIT license.

Jun 18 11

Finally blogging on my own webspace!

by pixelpracht

I have a domain, webspace and unlimitted traffic… there is no good reason beyond lazyness to not host my own blog.

lulz image

So, no more forwarding to wordpress.com for I found the time and bravery to make the move! :) I hope everything still works. In the days to come I’ll explore the new customization options that I now have.

Thanks to Barry from GamesChart.com for the nudge! :)

Mai 31 11

An asset pipeline in Flash. How we do it!

by pixelpracht
Here’s a real-world example of how we handle the assets in our current flash game project at my company. It’s a rather big browser game that uses several megabytes of resources (XML meta-data, PNG & JPEG Images, Sounds and Movieclips) that we have to deploy to the serves and load into the client when needed. In such a scenario managing the dependancies between the code and the assets can be quite challenging and timeconsuming.
This post is a little advanced and you should be allready familiar with embedding and dynamically loading resources in Flash.

The Challenge

The content creators create assets file by file and save them to a folder structure. Thanks to the magics of version control systems (SVN in our case) these ever growing amount of assets is synced between all collaborators. But someone has to make sure everything is available at runtime when the application needs it.
To embedd all resources using the [Embed] tag in the game’s source code would cause several problems: The size of the SWF would be huge as all assets that are potentially needed would have to be included. Each embedded resource has to be added when you build your project so compile times would explode. And as we’re using FlashBuilder we would have to write some lines of code for each embedd asset. But who’s going to maintain that? Gamedesigners and artists change, add and delete files to the repository but they don’t have the means (and inclination) to edit source code, so who’s keeping it synced?
A contrary approach is to put all resource files on server and load them at run time. But different types of resources require different code to load, if you require many resources at once you have to open one connection for each resource (adding a lot of overhead) and you have to keep track of multiple loaders. Lastly many resource files are compressed efficiently when embedded into a SWF and it’s sad to miss out on that kind of optimization.

Our Solution

So we’ve decided to setup an asset pipeline that converts our assets into a format that is more optimized to the needs of the runtime environment. Such a system is a common thing in “real” game development but unusual for flash game development – maybe because traditionally Flash applications are authored in an IDE that has build in functionality for asset management.
Flash Builder doesn’t have anything like that but luckily it’s based on Eclipse, a software development environment with an extensible plugin system. One plugin (part of the “Eclipse Java Development Tools”) adds support for “Apache Ant” build scripts to Flash Builder. Ant is a tool for automating software build processes. What to build with it? SWF’s that contain only assets as embedded resources, get uploaded to the server alongside our game SWF and when resource are needed the appropriate resource-packs are loaded at runtime to make the embedded assets available to Flash.
But our Ant script does a lot more then just invoke a compiler to build some AS3 files. It also generates these files on the fly. So the manual work required to embedd all our assets into some dozens of resource packs reduces to clicking a button.

The Details

So, what happens when we click?
Mrz 18 11

Matrix Magic

by pixelpracht
For a flash game project at work I needed to setup a flash.geom.Matrix instance to transform points from cartesian space into an isometric perspective.
To get it working I had to answer three questions:

1. How do the properties a, b, c, d, tx and ty map to the coefficients of the matrix?

Mapping of coefficeints in the Flash Matrix class

2. How to use the matrix to transform a Point?

The Matrix class provides two methods to transform a point.
  • deltaTransformPoint transforms a point without applying the translation.
x' = a * x + c * y;
y' = b * x + d * y;
  • transformPoint transforms a point including the translation.
x' = a * x + c * y + tx;
y' = b * x + d * y + ty;
If you know the mapping of coefficients and a bit of computer graphics that’s the expected behavior. To be able to multiply a 2D vector with a 3D matrix you introduce an extra 1 as 3rd component. Then perform a matrix multiplication. That way the transformation is added to x and y after the rotation/sheering is done.

3. How to setup the matrix to get the desired transformation?

If none of the provided methods fits your need (like in my case) you can set the correct values for the coefficients directly. That’s easier then it sounds. Look at the basis vectors of your source coordinate system and imagine (or calculate) how they look like after the transformation. Assign coefficients a the x and b the y value of the transformed x-axis. Assign the x and y value of the transformed y-axis to c and d.
If you need it you can set tx and ty to move the transformed points relative to the new origin.

And why do I blog about math, now?

Adobe managed to have a incorrect illustration of the layout of the coefficients in the german doc (english docs happen to be correct!) and the inscrutable description of the transformPoint and deltaTransformPoint methods lacked the specifics I needed. Let’s hope this post and the power of google will help those, that seek the same kind of knowledge!
Jan 7 11

Simulating Fluids in Flash

by pixelpracht

A thread in the FGL forums got me interested in the simulation of fluids. Of course this topic has seen quite extensive coverage in academic papers but getting it to work in the limitted environment of Flash provides some intersting challenges. Interesting enough for me to give it a try over my christmas break.

I loosely followed a paper Particle-based Viscoelastic Fluid Simulation to implement a sandbox application that simulates and renders a small blob of fluid and allows you to tinker with various parameters. Click the image below and give it a try!

The fluid is represented as a set of ~400 particles that interact with their neighbours and such seem to form a coherent entity.

For rendering I use an oldschool approach: Each particle is represented as a metaball. For a given pixel the force function of every metaball is evaluated, summed up and the final sum is compared with a threshold value to decide whether the pixel is inside or outside of the fluid.

To be able to do that in realtime I precalculate the values that a forcefunction yields for pixels within a relevant range of the particles center as a Bitmap.
Fluid Rendering - Illustration #1
These tiny images (about 40×40 pixels) are rendered at the position of the particle with additive blendmode.
Fluid Rendering - Illustration #2
Now I can decide with a single lookup in the resulting Bitmap if a pixel belongs to the surface or not. That evaluation step is done by a pixel bender shader and instead of just working with a boolean state (inside or outside) I sample a gradient based on the accumulated force value.
Fluid Rendering - Illustration #3
This approach allows me to achieve a variety of styles in the visual appearance of the simulated fluid by just using different gradients.

This technique would unfold it’s real potential if you could use hardware acceleration to accumulate the field functions because that’s a bottle neck in the current implementation.

Not sure if that stuff has any practical relevance, anyway. But the SWF is only 32kb big so people that are into demos (32k, 64k) could maybe make something fancy out of it. :) Here’s the source code released under the MIT license.

Sep 30 10

Developing and Selling Rune Hunt

by pixelpracht

I started experimenting with real time shadows in Flash in fall 2009. At the same time I took notice of the Flixel framework and all the cool retro games that people made with it. Why not make a game of my own that combines pixel graphics with dynamic light and shadows?

At the 14th December 2009 I created a thread in the Flixel forums with a mission statement:

The setup is classic: a hero in a dungeon full of treasure, traps and NPC of questionable attitude. The twist is that I’m limiting the player’s view to what his avatar is seeing. Top-down-ego-perspective so to speak. I hope it’s making exploring the dungeon more interesting and the enemies more scary if you don’t see all the stuff long before it becomes relevant/dangerous.

It’s been the beginning of an interesting journey…

read more…

Sep 24 10

Rune Hunt Released

by pixelpracht

Hungry eyes watch from the shadows. The flickering light of a butterfly is all that keeps them at bay. Run for your live – and sanity!

Finally, after almost a year of working on it, I have finished Rune Hunt!

Well, technically it’s been finished a couple of weeks ago. But I tried to find a portal that would sponsor the game. The basic idea of sponsorship is that you include links and logos of a flash game portal in your game before you spread it. The branding means traffic for the sponsor and that traffic is what they essentially pay you for. The other great thing besides money is that the sponsoring portal has an interest in getting your game played and will help spreading it – for example by featuring it on the front page. So you get money, exposure and retain full creative control. Cool stuff!

So in the last weeks I’ve spend quite a while on flashgamelicense.com and learned a great deal about how the market around free flash games works. The website is basically an agent that brings developers and sponsors together. Sponsors can bid on your games, after a while you pick the best offer and pay a comission to FGL. The process of trying to license my own game was nerve-wrecking but fun and in the end pretty successful. Huge thanks to ArmorGames for the generous sponsorship!

But enough of that for now. Go and play the game allready! ;)

Jul 6 10

Drawing API Memory-Leak in Flash 10.1

by pixelpracht

When trying Rune Hunt in the new 10.1 version of the Flash Player I noticed a HUGE performance drop. In the old player it would take about 27ms on my system (debug build) to update the game’s state and render the next frame. In Flash Player 10.1 this changed: The time it took to calculate a frame started fluctuating and increased to 48ms on average.

A member of the Flash Player Engineering team the new player replied to my inquiry about known performance issues:

General actionscript performance is not any slower in 10.1 than 10.0 from our testing, it must be something particular in your code which exhibits the problem. Do you have a reproducable test code or a url you can point us at?

So I tried to isolate and reproduce my problems. It seems that my problems are caused by a Memory Leak in the Drawing API. I wrote a simple test application to illustrate the issue and hopefully find a work-around.

 

//... there`s a buffer as rendertarget and a flare
private var _flare:BitmapData = null;
private var _buffer:BitmapData = null;
 
//each frame I render the flare 100 times into the buffer
for(var i:int = 0; i < 100; i++)
    _buffer.draw(_flare, null, null, BlendMode.ADD);

 

In the 10.0 player there is no memory fluctuation caused by this code. But in the 10.1 player each draw-call allocates new memory. The total memory is increasing linearily until the garbage collector kicks in. This of course effects the performance.

In all browsers and on all systems that I tested the memory leak was present in the new player – but the way the garbage collector handled it varied so the graph isn’t always as clear. You can test it for yourself. And here’s the source for the test application.

My guess at what happens: BitmapData.draw() method accepts IBitmapDrawable an interface that is implemented by all DisplayObjects and BitmapData objects. If you pass a BitmapData object however it seems like memory gets allocated based on the size of the render target. This memory is not reused or instantly freed but has to be collected by the garbage collector.

Knowing this there’s a neat workaround: If you wrap the BitmapData in a Bitmap before you draw it you can avoid the bugged code and the memory keeps steady!

 

//wrap _flare in a Bitmap (do this only once!)
_flareBmp = new Bitmap(_flare);
 
//now instead of _flare render _flareBmp
for(var i:int = 0; i < 100; i++)
 _buffer.draw(_flareBmp, null, null, BlendMode.ADD);
Jun 14 10

Resource Handling in Flash – Part Two

by pixelpracht

In the last post I showed two approaches to access resources such as sound or image data in Flash. To make resources available to your application you can either load resources one-by-one on demand or embed them all into the main SWF file so they are available as soon as the application has loaded. Both variants however have limitations. So in this post I’m going to show some alternatives.

read more…

Jun 2 10

Resource Handling in Flash – Part One

by pixelpracht

It’s easy to pickup ActionScript3 with a programming background in C++,/C# or Java as the languages shares the same concepts and similar syntax. So, why learn about stages and timelines, keyframes and whatnot when you can write your games like you always did? Well… almost. There are concepts in Flash that require some getting used to. Resources is one of them.

There are two fundamental different ways to get your resources loaded.

One is to embedd all the potentially needed data into your SWF file. This increases the initial loading time but once the application has fully loaded all resources are instantly available, too.

The second option is to send a lean application and load individual resources on demand. This is will reduce the initial load but making things less convenient for the coder and user.

read more…