Wednesday, April 25, 2012

How to Make UI Components for FlashPunk Games

It’s not easy to create the UI side of your game with FlashPunk, as it doesn’t include any UI components like buttons or text fields by default. This isn’t a restriction, though; it just means you’re completely free to create the UI exactly as you like. But you need to know how to do it first! This tutorial will teach you how to build some custom UI components, and show you the different ways you can customize them to exactly fit the style of your game.


Final Result Preview

Let’s take a look at the final result we will be working towards:

Step 1: Introduction

Many FlashPunk users tend to have problems with the UI side of their games. There’s no ‘easy’ way of making buttons and other interactible-elements like text fields or checkboxes, for example, in FlashPunk. No Button class.
That may seem of a restriction, yes, and many newcomers find it a little bit confusing at first… but there’s a reason behind that. Games, each one of them, tend to have a custom user interface unique to themselves, which design is related to the mechanics or theme of the game itself. You won’t see any good game (generally speaking) that has the default window buttons for its controls!
We could argue that, in this case, there could be some classes providen with the bare-bones of the functionality, the minimum required for some buttons to work, and leave the graphic side to the user… yes, that is true… but the generalization we would have to use in those classes would be either too big and confusing or too specific and not costumizable enough. (believe me, I was in charge of the semi-failed semi-working Punk.UI project.) We will learn how to code our own components instead!
So what this tutorial is going to show you is how to build your own UI elements for your game in FlashPunk, give them behaviour, and show some tricks to make their graphic part with the most used techniques… but remember that each of your games will need a different UI graphically-wise!
As the tutorial is really lengthy, it’s been divided into multiple parts. This first part will teach you how to build each component, without the eye-candy and costumization. We will introduce these later.
To code the example SWF with our UI, we are going to use FlashPunk, as this is a FlashPunk tutorial, and FlashDevelop for the IDE. If you feel more comfortable with another IDE, like FlashBuilder, you are free to use that, just adapt the specific parts of this tutorial.
Previous knowledge on FlashPunk is needed to follow this tutorial. This is not a general FlashPunk tutorial, this is a UI tutorial using FlashPunk. If you don’t know FlashPunk, you can take a look at the Introductory FlashPunk tutorials on Activetuts+ and also check out the official FlashPunk tutorials.
Read more: How to Make UI Components for FlashPunk Games

My ActionScript Game Server with 15,000 Concurrent Connections

Goal

Create a game using ActionScript for both the server side game server and the client side game with the ability for high concurrent (10,000+) socket connections. Make sure memory and performance of the application are up to the task.

What am I talking about?

This blog post will explain how I was able to create a socket server running on a Amazon EC2 ubuntu server with more than 15k+ concurrent connections. This socket server has all the game logic for a game called SpellTraction, which both the server and client are written in ActionScript.
Server: Game built in ActionScript 3 and run as a shell process using a modified redtamarin build. The modified redtamarin has a libev based socket server.
Client: Client game built with ActionScript 3.
To check out a running version of the client go to either:
http://renaun.com/serveras/test/ - this version is driven by other Amazon EC2 instances that are running test scripts to create the 15k+ connections.
or
http://renaun.com/serveras/spelltraction/ - the game with any other player looking at it right now.

Here is a screenshot of the game [...]
Read more: My ActionScript Game Server with 15,000 Concurrent Connections

Monday, April 23, 2012

ActionScript 3.0 Bitmaps, Clones and ColorTransforms

Color Bit TransformLess is More Ever since I started working with mobile devices with Flash and ActionScript 3.0, I’ve been looking for faster ways to move my objects through those little windows on iPhones, Androids and Blackberries. Lag time is huge and the action looks geriatric. I’ve seen some interesting things done with the bitmapped classes, and in previous posts we’ve discussed what may be helpful. However, since I haven’t used them extensively (or fully), I thought it’d be a good idea to walkthrough my thinking on the topic. For a while now I’ve been working on a a Samurai action game, and while I’ve been making progress, I keep looking for speed tweaks. In general my thoughts regarding bitmapped graphics and Bitmap classes can be summed up in Figure 1. If I create a single Bitmap object using the BitmapData objects (or convert graphic files into BitmapData elements) and then clone the object, I should be able to save processing time.
Figure 1: Cloned and Colored
Of course, I have to assume a good deal. First, I assume that processing a single instance of an object and cloning it is more efficient than creating multiple instances of the same object. I got the idea from how Flash originally used symbols over the Internet. You create one symbol and then re-used it. My idea is pretty much the same. Create once; clone many. Second, in order for an object to look like more than a single object, I want to change something about the cloned object. With my simple samurai fighter, I can change its color because it is a Bitmap object. So, first we’ll look at how to create a bitmapped object from scratch using both the Bitmap and BitmapData objects. Making Bitmapped Objects from Code I like drawing bitmapped objects or using digital photography. However, in order to best understand what’s going on, let’s start from scratch with BitmapData objects. Figure 2 shows the fundamentals of creating a bitmapped data object:
BitmapData Figure 2: Implementing BitmapData Object
The ActionScript 3.0 BitmapData object contains a 32-bit integer made up of four 8-bit values (0-255). The first parameter expects a width, the second height—this is the Bitmap shape; a rectangular data matrix. The third parameter is the objects transparency, which has a default value of true (it is transparent). By setting the transparency argument to false, you make the object opaque. The 32-bit integer is the final parameter with the first two hexadecimal values being the alpha value with the final six values expressing an RGB color. The following class provides a basic example: [...]
Read more: ActionScript 3.0 Bitmaps, Clones and ColorTransforms

Monday, April 16, 2012

ActionScript 3.0 Optimization: A Practical Example

Code optimization aims to maximize the performance of your Flash assets, while using as little of the system’s resources – RAM and CPU – as possible. In this tutorial, starting off with a working but resource-hogging Flash app, we will gradually apply many optimization tweaks to its source code, finally ending up with a faster, leaner SWF.


Final Result Preview

Let’s take a look at the final result we will be working towards:
Note that the “Memory Used” and “CPU Load” stats are based on all the SWFs you have open across all browser windows, including Flash banner ads and the like. This may make the SWF appear more resource intensive than it actually is.

Step 1: Understanding the Flash Movie

The Flash movie has two main elements: a particle simulation of fire, and a graph showing the animation’s resource consumption over time. The graph’s pink line tracks the total memory consumed by the movie in megabytes, and the green line plots CPU load as a percentage.
ActionScript objects take up most of the memory allocated to the Flash Player, and the more ActionScript objects a movie contains, the higher its memory consumption. In order to keep a program’s memory consumption low, the Flash Player regularly does some garbage collection by sweeping through all ActionScript objects and releasing from memory those no longer in use.
A memory consumption graph normally reveals a hilly up-down pattern, dipping each time garbage collection is performed, then slowly rising as new objects are created. A graph line that’s only going up points to a problem with garbage collection, as it means new objects are being added to memory, while none are being removed. If such a trend continues, the Flash player may eventually crash as it runs out of memory.
The CPU load is calculated by tracking the movie’s frame rate. A Flash movie’s frame rate is much like its heartbeat. With each beat, the Flash Player updates and renders all on-screen elements and also runs any required ActionScript tasks.
It is the frame rate that determines how much time Flash Player should spend on each beat, so a frame rate of 10 frames per second (fps) means at least 100 milliseconds per beat. If all the required tasks are performed within that time, then Flash Player will wait for the remaining time to pass before moving on to the next beat. On the other hand, if the required tasks in a particular beat are too CPU intensive to be completed within the given time frame, then the frame rate automatically slows down to allow for some extra time. Once the load lightens, the frame rate speeds up again, back to the set rate.
(The frame rate may also be automatically throttled down to 4fps by the Flash Player when the program’s parent window looses focus or goes offscreen. This is done to conserve system resources whenever the user’s attention is focused elsewhere.)
What this all means is that there are actually two kinds of frame rates: the one you originally set and hope your movie always runs at, and the one it actually runs at. We’ll call the one set by you the target frame rate, and the one it actually runs at the actual frame rate.
The graph’s CPU load is calculated as a ratio of actual to target frame rate. The formula used to calculate this is:
CPU load = ( target frame rate - actual frame rate ) / actual frame rate * 100
For example, if the target frame rate is set to 50fps but the movie actually runs at 25fps, the CPU load will be 50% – that is, ( 50 - 25 )/ 50 * 100.
Please note that this is not the actual percentage of system CPU resources used by the running movie, but rather a rough estimate of the actual value. For the optimization process outlined here, this estimate is a good enough metric for the task at hand. To get the actual CPU usage, use the tools provided by your operating system, e.g. the Task Manager in Windows. Looking at mine it right now, it shows the unoptimized movie is using 53% of CPU resources, while the movie’s graph shows a CPU load of 41.7%.
ActionScript 3.0 Optimization: A Practical Example

Saturday, April 14, 2012

ActionScript 3.0 Bitmap Classes: The Bitmap Factory Method At Work

Bitmap Factory Method At WorkBuilding a Bitmap Factory
The idea of taking a perfectly good graphic file and taking it apart and putting it back together again has a surprising appeal. You may wonder why one would want to do that? For me, it’s a chance to explore the Bitmap classes built into ActionScript 3.0 and see if there is some way to manage the pixel set better and learn as much as possible about the behavior of bitmap data, filters and anything else that might be useful for speeding things up.
More importantly for design pattern development is creating bitmap data objects and moving them around between participants in a pattern and making changes and additions to a program. In creating this pattern, I found it relatively easy to create a concrete product class from an abstract class used in loading and changing standard bitmap files into ActionScript 3.0 bitmap code; however, I had to spend some time calling for a bitmap object through a creator. In other words, getting something up on the stage using a Factory Method design pattern was more than just duplicating what I had done before with the Loader class and bitmap graphic files.
To get started, download the files used and take a look at the outcome by pressing the Play button.
play buttondownload this sucker
You will find examples from three types of bitmapped graphics: GIF, JPEG and PNG. Identical code was used to break them into bitmap objects from ActionScript 3.0 classes.
The Bitmap Product
The design participants to see first are the abstract and concrete bitmap products (BitMapProduct, BitMapSam). The abstract class contains the properties used in both loading the bitmaps and working with Bitmap and BitmapData properties and methods. [...]
Read more: ActionScript 3.0 Bitmap Classes: The Bitmap Factory Method At Work

Thursday, April 5, 2012

Predicting Collision Points With Math in AS3

In my previous tutorial about collision detection between a circle and a line, I covered projection on a line using the dot product of a vector. In this tutorial, we shall look at the perpendicular dot product and use it to predict the point of intersection for two lines.


Final Result Preview

Let’s take a look at the final result we will be working towards. Use the left and right arrow keys to steer the ship (triangle), and press up to boost the speed temporarily. If the projected future collision point is on the wall (the line), a red dot will be painted on it. For a collision that “already” happened (i.e. would have happened in the past, based on the current direction), a red dot will still be painted but slightly transparent.
You can also mouse click and drag the black dots to move the wall. Note that we don’t just predict the location of the collision, but also the time.

Step 1: Revision

Before getting into the topic, let’s do some revision. Here’s the dot product equation (previously covered here):
dot product formula
And here’s the perpendicular dot product definition as extracted from Wolfram:
perp dot product formula

Step 2: Perpendicular Dot Product

Now to help us form a mental picture, I’ve prepared the image below. I’m confident at this point you are able to derive the vertical and horizontal components of a vector, so the components involving sine and cosine shouldn’t be a challenge.
a mental picture for two formula
Let’s substitute both components with their equivalent. I have used A with a hat to represent the unit vector of A (that is, a vector that points in the same direction as A, but has a magnitude of exactly 1). Another detail is that the perpendicular of B is actually the right normal of B – more on normals next step.
second mental picture for two formula
From the diagram above we can see that the projection of B on A will produce |B|*cos (theta). But why would the projection of B’s normal produce |B|*sin (theta)? [...]

Read more: Predicting Collision Points With Math in AS3