Flash Game Development with Flex and Actionscript - Double Buffer Rendering (Page 2 of 2)

Article by Matthew Casperson (4,883 pts ) , published Nov 5, 2009

GameObjectManager.as

package

{

import mx.core.*;

import mx.collections.*;

import flash.display.*;

public class GameObjectManager

{

// double buffer

public var backBuffer:BitmapData;

// colour to use to clear backbuffer with

public var clearColor:uint = 0xFF0043AB;

/// static instance

protected static var instance:GameObjectManager = null;

// the last frame time

protected var lastFrame:Date;

static public function get Instance():GameObjectManager

{

if ( instance == null )

instance = new GameObjectManager();

return instance;

}

public function GameObjectManager()

{

if ( instance != null )

throw new Error( "Only one Singleton instance should be instantiated" );

backBuffer = new BitmapData(Application.application.width, Application.application.height, false);

}

public function startup():void

{

lastFrame = new Date();

}

public function shutdown():void

{

}

public function enterFrame():void

{

// Calculate the time since the last frame

var thisFrame:Date = new Date();

var seconds:Number = (thisFrame.getTime() - lastFrame.getTime())/1000.0;

lastFrame = thisFrame;

drawObjects();

}

protected function drawObjects():void

{

backBuffer.fillRect(backBuffer.rect, clearColor);

}

}

}

The GameObjectManager object will be responsible for managing the elements that will make up the final game like the enemies, the player and the various background elements. It is also responsible for managing the back buffer to which these elements will draw themselves to. If you recall the front buffer was implemented as a canvas element. This was for convenience as a canvas can be added directly as a child of the Application object. The back buffer is implemented as a BitmapData object, which allows us to quickly and directly manipulate the pixels that make up the final image.

The clearColor property specifies the colour that will be used to wipe the back buffer before the scene is built up. Eventually the entire back buffer will be overwritten by the game elements, which makes this color irrelevant, but for now it is quite important because it will make up a good chunk of the final frame. The value 0xFF0043AB is a dark blue. The first two hex values (those after the 0x) represent the alpha: FF for opaque and 00 for transparent. The next 6 hex values make up the red (00), green (43) and blue (AB) components.

The static instance property is used with the Instance function to implement the Singleton design pattern. Basically we only ever want one GameObjectManager to exist in the program (hence the name), and by referencing the GameObjectManager through this instance property we can be assured that only one GameObjectManager will ever be created. The Singleton design is quite a common programming paradigm, and while ActionScript lacks support for a protected constructor it still useful as a self documentation tool (if you ever see an Instance property, chances are that the object is designed as a Singelton).

The lastFrame property simply stores the time when the last frame was renedered. By keeping a track of this time we can determine how long it has taken between the last frame and this current one, which (will eventually) in turn allows us to update the game elements by this amount. Even though we don’t have any game elements yet the time between frames is calculated in seconds during the enterFrame function. The lastFrame time is reset during a call to startup. This is because the GameObjectmanager is not updated while the program is not in the Game state. If we didn’t reset lastFrame the first frame of the next level would be equal to the time the player spent in the menus inbetween levels. The player could end up jumping halfway across the level during the first frame, which is definitely best avoided.

So, what have we achieved here? By implementing states we have created a menu screen, from which the player can enter the game by clicking a button. The “game” itself is just an implantation of a double buffer, which draws a blue background. However with the states and rendering implemented we can finally get to the fun stuff: drawing to the screen.

Related Files

Showing page 2 of 2

22 Comments

Showing page 1 of 3 (22 Comments)
Oct 24, 2009 6:19 PM
RE: Flash Game Development with Flex and Actionscript - Double Buffer Rendering
Your right, as it stands you could create multiple instances of the GameObjectManager. To be perfectly honest I copied and pasted this code from a snippet I found elsewhere and didn't actually look too closely at the implementation :(
Oct 24, 2009 12:53 PM
Bobby
Singleton - Last Post
Hmm, you keep pointing me back to the basics. If I'm missing something, I apologize, but I can't help but feel that my affinity for understatement has led you to underestimate and dismiss me. Let me try being bolder. I do not believe the Singleton method used here works the way you think it does. Maybe an example will serve better.

I can do this (as well as use any other functional part of the class)...

var clsGOM_1:GameObjectManager = new GameObjectManager();
clsGOM_1.EnterFrame();

var clsGOM_2:GameObjectManager = new GameObjectManager();
clsGOM_2.EnterFrame();

var clsGOM_3:GameObjectManager = new GameObjectManager();
clsGOM_3.EnterFrame();

...all day long and it will never throw the warning error. Why? Because instance (prop) defaults to null and as long as I don't use Instance (method), it will always remain that way. As long as instance remains null, the if statement in the constructor will never be true despite the fact that I've made 3 (and could have made infinitely more) instances of your object. Unless I'm missing something, the Singleton method used here just doesn't cover the most prime/elemental/fundamental thing that it should be covering.

I doubt either of us has any more time/energy for a topic that isn't critical to this tutorial. The only thing I might argue is that if you're going to include some potentially confusing code in a tutorial that's likely to attract a lot of new developers, it should do what's intended. Otherwise, it's even more confusing.

I've since looked at this code at a site you pointed me to: http://en.wikipedia.org/wiki/Singleton_pattern#Flash_ActionScript

Assuming it works, which is predicated on the necessity that a class constructor executes before any class properties (in this case INSTANCE) are assigned their default value, then it would appear to actually prevent new instances from being created (not just warn about it). That would be the best method I've seen yet.

All the best.
Oct 23, 2009 8:16 PM
Singleton
Your approach is essentially what the original code does. Inside the constructor we look to see if the instance (notice the lower case "i") variable is null. If it is, the instance variable is set to the value of the current object and everything is good. However, if the instance variable is not null that means the constructor has been called at least once before and an exception is thrown.

The Instance property (notice the uppercase "I") provides access to the instance (the lowercase one) variable, initialising it if it is null.

The only real difference with this approach as opposed to yours is that the Instance property provides a central location to access the single instance, rather than having to record the value returned by the constructor after the first call in your own code.
Oct 23, 2009 12:09 PM
Bobby
Singleton Implementation
Okay, I figured out that my confusion centered on the static keyword. I was under the impression that it was just for scope. I didn't realize the implication on properties (namely, that all instances of an object share the same value for that property).

I'm a little confused though. In my short run at this I've bumped into (but not really studied) several articles about Singleton in ActionScript. It seems to be a hot topic of argument among people smarter than I. Still, I don't think I heard anyone saying there was a way to strictly invoke it...only to inform the developer much in the way the method used here does. To that end, I don't know why this is complicated. The problem I see with the method used here is that it doesn't appear to inform the developer during the most likely misuse of the object. Typically, you use objects by creating instances of them with variables (not calling the class directly). A person could *innocently* create multiple instances with variables and then fully use every functional part of it. As long as they never use the Instance method (and if they're not initiated on Singleton, why would they even think to?), they would be none the wiser because the constructor error would never, ever be thrown.

The answer seems (too?) simple:
-----------------------------------------------
add a global property -
private static iNumInstances:uint=0;

change your constructor -
iNumInstances = iNumInstances + 1;
if (iNumInstances != 1) {
Alert.show("Invalid Singleton use. Please fix.") }

It's a static property, so it should increment on any attempt to create a new object. At this point you could optionally get rid of the instance property and Instance method altogether. That would be a style choice. The main thing is that this bit of code covers the most likely misuse of the object.

What am I missing? It couldn't be that simple, could it? Feel free to criticize. It's all about learning :)
Oct 23, 2009 5:40 AM
Bobby
Singleton Implementation
Okay thanks. I guess the source of my confusion was how to trip a constructor for an instance of an object more than once. After spending a couple hours not being able to do it, now I find myself doing it all the time and for reasons I don't quite understand. Ah, but I guess those are questions for another forum :)

Cheers
...and thanks for the tutorial and so actively supporting it.
Oct 22, 2009 5:29 PM
Singletons
Singletons in ActionScript are complicated because you can not have a protected or private constructor. In a language like C++ a singleton would be defined (and enforced by the compiler) thanks to the fact that an outside class could not call the protected constructor (in conjunction with the new keyword).

In Actionscript you have to settle for throwing an exception when more than one instance of an object is created. It won't actually stop more than one instance being created, but hopefully it will make a developer stop and think about the reason why more than one instance is needed (rather than catch the exception and ignore it).

See http://en.wikipedia.org/wiki/Singleton_pattern#Flash_ActionScript and http://www.darronschall.com/weblog/2007/11/actionscript-3-singleton-redux.cfm for more info.
Oct 22, 2009 11:14 AM
Bobby
Singleton Implementation
Hi Matt, I'm 72 hrs (minus sleep/eat/poop) into this whole Flash/Flex/MXML/ActionScript thing. In fact, I got started by finding your tutorial and dowloading the tools you suggested. I spent a few hours doing your first 2 chapters and then switched to pouring through Adobe docs to get a better feel for the structure/language. Consequently, I know just enough to be dangerously ignorant :)

Anyway, I'm back to your tutorial and want to ask you about your Singleton implementation before I proceed to Chapter 3. Namely, I don't get its reasons/consequences. As near as I can tell, there's nothing that prevents another developer from creating countless instances of the GameObjectManager class with object variables and then using all the properties and methods other than instance (property) and Instance (method). On the plus side, if one were to use object variables in concert with Instance, they would get a compile error. If that's all it was, I suppose I could see an argument for it. What I'm baffled by is the inclusion of the "throw new Error" statement. I get how that would end execution of that function, but what I don't get is when that would ever be triggered. To my (pea-brained) way of thinking, you could create many instances of an object with object variables, but if you're referencing the class definition directly by name (possible source of confusion), could there ever be more than one? And even if there could, I'm thinking each instance property would be tied to itself. I mean I can create countless instances of the object with variables and that error is never triggered because it's not actually looping through and testing all the objects that are part of the application.

So, I just don't get it. Any explanation would be appreciated, but if you could just provide an example of how to trip that code, that would probably illuminate for me its purpose and perhaps give me some insight into Flex/ActionScript object creation.

Much obliged :)
Oct 5, 2009 1:23 PM
Aki
Double buffering
Hello, it's me again.
I ran some tests with double buffering vs. not.

http://pastebin.im/118
http://pastebin.im/119

Couldn't get a clear winner. I thought it might be a difference with the filling, but when I tried with only 2 objects:

http://pastebin.im/120
http://pastebin.im/121

I couldn't get a clear winner either. Without double buffering it seems to be very slightly faster, but they're so close it could be just a statistical error. Here are the results I got:

http://pastebin.im/122
Oct 5, 2009 8:42 AM
Aki
game loop
Erf, of course I messed up and put the "currentTime = new Date().getTime()-dt;" in the wrong place. Of course that's not the place for initialization variables...

Also forgot the pluses from the "loop", like sigs mentioned.
Oct 4, 2009 4:28 PM
sigs
a maths/physics note...
"With the example of the asteroids clone, your claim that the acceleration is based on your FPS in not correct. Technically your acceleration would be a fixed value, and the amount that your ships moves would be determined by a formula like s = ut + 0.5 at^2"

actually, that's not true. Try it out with pen and paper. If you do

v += a * dt;
s += v * dt;

you get different s for different dt.
Showing page 1 of 3 (22 Comments)
 
Subscribe to Web Development
RSS
Get free weekly updates, directly to your inbox.
Subscribe
Browse Web Development