Archive for the ‘ActionScript 3.0’ Category

FIVe3D TextCloud: AS3 Tutorial and Source

Friday, May 23rd, 2008

A few people have asked me to release the code to my FIVe3D Text Cloud example, so I’ve cleaned things up to the point where I wouldn’t be completely humiliated to release it into the wild. However, I thought I’d touch on a couple points and turn this post into something halfway between a tutorial and an exhibition.

If you just want the source code, you can download it at the bottom of the page. If you’d like the whole shebang, pray read on.

The (new and improved) example:

FIVe3D Basics

FIVe3D is ridiculously easy to set up. In this example, I used the following code to set up everything I needed:

// the Scene3D class is what contains and renders everything else
// think of it as a 3D Stage class
scene = new Scene3D();
scene.x = 375;
scene.y = 200;
addChild( scene );
 
// Sprite3D is, obviously, a 3D version of the standard Sprite class
// it is an actual DisplayObject, so you can use normal positioning, filters, etc. on it
container = new Sprite3D();
scene.addChild( container );

You’ll notice that the syntax is just like AS3 extended into the third dimension. You can nest Sprite3Ds just like Sprites. When you move or rotate the parent Sprite3D, the children will move and rotate with it. The reason I’ve created a container Sprite3D here is so I can rotate several children at the same time.

Now if I wanted to do this the easy way, I could just add my text in one big chunk with the DynamicText3D class that ships with FIVe3D. It works much like the AS3 TextField class, except that the fonts are actually ActionScript files (you’ll see what I mean when you crack open the FIVe3D source).

var txt:DynamicText3D = new DynamicText3D( HelveticaBold ); // HelveticaBold ships with FIVe3D
txt.size = 30;
txt.color = 0xD34328;
txt.text = "Pixelwelders LLC"
container.addChild( txt );

That’s it. The Scene3D class takes care of its own rendering, so you don’t have to trigger it yourself, Papervision-style. Even when a FIVe3D scene looks static, it is actually rendering at your current frame rate. Thus, this is enough code to render 3D text in FIVe3D. Add an ENTER_FRAME listener and increment the container.rotationX property every frame and you’ll see what I mean.

Moving On…

Now this is fine for your everyday run-of-the-mill 3D text, but not for the effect that I had in mind. If I had added my text this way, it would have behaved as a single block, each letter forever doomed to stay wedged firmly between its neighbors. No, I had bigger plans for this text.

For this effect, I created a class called MotifCollection3D. Not a very good name, but typography is not my strong suite and I wasn’t quite sure what else to call it. It’s an extension of the aforementioned FIVe3D Sprite3D class, and it contains one DynamicText3D instance for every letter of the word that it’s currently displaying. This is how you instantiate it:

var cloud:MotifCollection3D = new MotifCollection3D( "PIXELWELDERS LLC", HelveticaBold, 30, 0xD34328 );
container.addChild( cloud );

There’s nothing to it. You send the text, the font class (again, included with FIVe3D), the size, and the color. It creates and assembles all the DynamicText3D instances, and then you can treat it like any other Sprite3D. However, it also includes two methods: assemble(), and the thrillingly-named explode().

Calling either of these methods cycles through all the instances of DynamicText3D and tweens them each to a destination using TweenLite. The explode() method was easy: it just chooses a random destination and rotation for each letter. The assemble() function, on the other hand, was a bit trickier; it needs to know the exact width of every letter in order to place them next to each other.

Happily, that is one of the things that’s included with the FIVe3D typography classes. Each letter, number, and punctuation mark in HelveticaBold contains a __width property, accessible like so:

var letterWidth:Number = HelveticaBold.__widths[ "P" ]; // returns the width of the "P" glyph

That’s a start, but it returns the same width regardless of what size the font is being displayed at. After a little experimentation, I found that this code gives the correct glyph width no matter what size the font:

var letterWidth:Number = HelveticaBold.__widths[ "P" ] * ( size / 100 );

I think that pretty much covers anything novel that I may have done. There are additional comments in the code as well, and it’s only two classes anyway: it shouldn’t be too difficult to figure out anything not explicitly laid out here.

Download Source

Pixelwelders FIVe3D Text Cloud

NOTE: You’ll need to download TweenLite and FIVe3D from their respective sites to get this to run. But you probably already knew that.

Best FIVe3D Experiment Yet- Seriously, It’s Awesome

Monday, May 12th, 2008

The FIVe3D examples are starting to fly hot and heavy through the blogosphere, so here’s another contribution. This will probably be the theme of my new portfolio, but I was so impressed with the result that I had to post it. This will be perfect with a bit of scratchy 1920’s horn music.

AS3: BitmapData Foibles

Monday, May 5th, 2008

Today I ran into what looks like an odd oversight in Adobe’s otherwise excellent BitmapData class. Alternatively, it could be an oversight in my otherwise excellent critical thinking skills. Neither is unheard of, but either way, someone is missing something somewhere.

Here’s the scenario: I had loaded an image via a Loader, and I wanted to capture a chunk out of the middle of it. For the sake of this example, let’s say I wanted a 200×200 square, starting at (50, 50) in the source image. So, foolishly and naîvely, I used this code:

	// create the BitmapData and draw() the contents of sourceImage into it
	var bmpData:BitmapData = new BitmapData( 200, 200, true, 0x00000000 );
	bmpData.draw( sourceImage, null, null, null, new Rectangle( 50, 50, 200, 200 ), true );
 
	var bmp:Bitmap = new Bitmap( bmpData, PixelSnapping.ALWAYS, true );
 
	// add to display list

So imagine my surprise when I got this:

Unexpected BitmapData behavior

This was definitely not what I was expecting, but apparently it is the intended functionality of BitmapData.draw(). I expected this image to line up with the upper left corner of the Bitmap container but as you can see, it doesn’t. It does indeed start copying pixels at (50, 50) on the source image, but when added to a Bitmap, it begins drawing those pixels at (50, 50) as well. That means that the whole thing is shifted 50 pixels along both axes, leaving empty space at the top and left while cutting off pixels at the right and bottom. This, to me, seems like a Bad Thing.

I’ve played with this for a couple hours now and I can’t find a way to do this without resorting to what I think most people would term a “workaround.” This is why I think that either Adobe just left out something, or (more likely), that I am just not grasping how this whole BitmapData/Bitmap thing works.

Anyway, this is my workaround. In my traversals of the AS help files, I noticed that there is a method that allows you to specify both things that I need: coordinates of a set of pixels on the source image, and coordinates for where to put said pixels on the target image. That method is BitmapData.copyPixels. However, it only works between two instances of BitmapData.

So, I created two instances of BitmapData. To make it easier to use, I placed it in a static class called BitmapGrabber.

public static function grab( source:DisplayObject, rect:Rectangle, smoothing:Boolean ): BitmapData
{
 
	if( !source is IBitmapDrawable )
	{
		throw new Error( "Cannot create BitmapData.  Source must implement IBitmapDrawable" );
	}
 
	var bmpData1:BitmapData = new BitmapData( source.width, source.height, true, 0x00000000 );
	var bmpData2:BitmapData = new BitmapData( rect.width, rect.height, true, 0x00000000 );
 
	bmpData1.draw( source, null, null, null, null, smoothing );
	bmpData2.copyPixels( bmpData1, rect, new Point( 0, 0 ) );
 
	bmpData1.dispose();
 
	return bmpData2;
}

And this is me using the class:

// create the BitmapData and draw() the contents of sourceImage into it
var bmpData:BitmapData = BitmapGrabber.grab( sourceImage, new Rectangle( 100, 100, 100, 100 ), true );
var bmp:Bitmap = new Bitmap( bmpData, "auto", true );
 
// add to display list

And this is what I get:

Bitmap success!

It’s a ridiculously simple solution. However, I feel so strongly that BitmapData should have this capability (without a workaround), that I can’t shake the feeling that it must have this capability and I am just missing it. But, until some member of the Flash community tells me a better way to accomplish this, this is the class I’ll be using in my code.

FIVe3D and TweenLite: Text Cloud

Monday, April 28th, 2008

UPDATE: I have another FIVe3D example/experiment (3D graphing) here. And, if you’re just cruising the web for FIVe3D examples, I have yet another one here.

I can’t seem to get enough of this FIVe3D thing. It’s even becoming natural to capitalize every letter except for that “e” when I write it. Not that I’m blinded to its faults, for there are a few here and there. But for quick 3D text rendering, I have yet to find its equal.

Take today’s experiment, for example. It was originally a Twitter viewer, but I haven’t figured out how to get it working online yet, so I’ve given it some generic text to render. It uses TweenLite for movement, and FIVe3D for rendering. Try clicking around and moving the mouse.

The part of this project that would have been challenging in PV3D or Sandy is the spacing of the letters. It was a great relief to find that FIVe3D is already intimately aware of each letter’s size, since it is rendering them as shapes. Thus, I didn’t have to painstakingly experiment to find the proper spacing.

Once I actually think up a clever tagline, I might just turn this into my site header. This could also be a pretty slick little tag cloud for site content, but I think it might get annoying if this was the only way to find a category. Ah well. A man can dream.

UPDATE
I did indeed turn this into my header. We’ll see how many people play with it.

UPDATE #2
And… I took it back out. Seems that something was weird with IE and Kimili Flash Embed. Or… it could have been user error.

UPDATE #3And… source code is live! With a tutorial/walkthrough, even! Get it here:
FIVe3D TextCloud: AS3 Tutorial and Source

The Art and Beauty of Singletons

Monday, April 14th, 2008

What is a Singleton?

A) In poker, a card that is the only one of its rank.
B) In animal husbandry, the sole surviving offspring of a litter.
C) In astrology, a single planet alone in a hemisphere (or some crap like that).
D) In mathematics, a set with only one member.
E) In England, a small village about 7 miles north of Chichester in West Sussex.

A cute yet tragic Singleton

All of these things share a trait, and that trait is that each is the only one of its kind. If two kittens survive from a litter, neither one is a singleton. If a set has more than one number, it is not a singleton. In works the same way in object-oriented programming; a Singleton is a class that allows only one instance of itself; if there are more than one, that class cannot be a Singleton.

So why would one want a class that only allows one instance of itself? I can think of many applications. A ScoreKeeper class for your game, perhaps, or a Countdown class that keeps track of how much time you have to complete a level. In OS Wars I use a Singleton to keep track of all building resources currently in the game. There’s another one that keeps track of all the units on the battlefield. In fact, the Battlefield itself is a Singleton, because there’s no reason I would ever need more than one.

Another great thing about a Singleton is that, because there is only one, it’s very easy to get to. With a normal object, you have to worry about passing it around to the various classes that might need it. With a Singleton, that’s not necessary. All you need to do is import the class and voilà- there’s your Singleton.

The Village of Singleton

It works this way because the class itself keeps a static reference to the only instance of itself. So instead of calling the constructor to get a reference to a new instance, you call the SingletonClassName.instance method to get a reference to the already-created instance. If that doesn’t make sense, here’s an example. This first piece of code is what a normal ScoreKeeper class would look like. With this structure, you can use that syntax that everyone knows and loves, new ScoreKeeper(), which returns a brand new ScoreKeeper every time it’s called.

package
{
	public class ScoreKeeper
	{
		public function ScoreKeeper()
		{
			trace( "new ScoreKeeper" );
		}
	}
}

But suppose you wanted to ensure that there was only one ScoreKeeper, and you wanted to be able to easily access it from any location in your program. That means two things: A) the constructor can only be called once, and B) you need to keep track of the new ScoreKeeper that one time the constructor does get called. What good is having one instance of a class if you can’t get to it? So here’s the Singleton version of the above class:

package
{
	public class ScoreKeeper
	{
		private static var _instance:ScoreKeeper;
 
		public static function get instance()
		{
			if ( !_instance )
			{
				_instance = new ScoreKeeper();
			}
 
			return _instance;
		}
 
		public function ScoreKeeper()
		{
			trace( "new ScoreKeeper!" );
		}	
	}
}

There are two differences here: the static variable _instance and the static method get instance(). The _instance variable is where the actual instance of this class is stored. And the get instance() method, of course, enables you to access this instance. So to access this Singleton, you would use:

ScoreKeeper.instance;

And to call any methods or properties of the Singleton, you would use this syntax:

ScoreKeeper.instance.addScore( 50 );
trace( ScoreKeeper.instance.score );

This of course assumes that your class has a public method called addScore() and a public property called score. You can get to any public methods or properties this way.

This also adds one more layer, called lazy initialization. Look in the get instance() method, and notice that before it returns a reference to the Singleton, it checks to see if that reference exists. If so, it simply returns it. If not, it creates it first and then returns it. Either way, you’re guaranteed to get the one existing instance.

There is one problem remaining- if you were so inclined, you could still call the constructor without going through get instance(), which would of course result in two Singletons. And as we discussed above, making two of something makes it not a Singleton anymore. So how can we prevent this? There are a few ways I’ve seen floating around, but the simplest is this:

package
{
	public class ScoreKeeper
	{
		private static var _instance:ScoreKeeper;
 
		public static function get instance()
		{
			if ( !_instance )
			{
				_instance = new ScoreKeeper();
			}
 
			return _instance;
		}
 
		public function ScoreKeeper()
		{
			if ( _instance )
			{
				throw new Error( "Singleton already exists- use get instance() to access" );
			} else {
				trace( "new ScoreKeeper!" );
			}
		}	
	}
}

The new lines are in the constructor. The get instance() method still only calls the constructor once, but if you forget it’s a Singleton and call the constructor later, you get a runtime error.

There are also a couple more complicated ways of ensuring that your Singleton is in fact a Singleton, but I haven’t lost too much sleep over over it. I usually even leave out the check in the constructor. Just remember that if it has _instance and get instance(), and a big comment up at the top that says “SINGLETON!”, it’s probably a Singleton.

MXML Singletons in Flex 3

Thursday, April 10th, 2008

If you’re not clear on what a Singleton is, try glancing through my brief yet poignant article here: The Art and Beauty of Singletons.

Creating a Singleton through MXML

Okay, so I’ve been putting together a little image-viewer component in Flex, and I wanted it to load one data model that all other components would share. Sounds like a job for a Singleton, right? However, I also wanted to instantiate said model from MXML, which adds some kinks. In fact, I’ve heard it said that it’s not possible at all. And after some trial and error, I found that apparently it is possible- you just have to hack around a little bit.

If you instantiate your class (or “component”) through MXML, Flex will automatically call its constructor. Typically, this is a bad thing because you don’t call constructors directly in Singletons- instead of calling a method that returns a new object (i.e. a constructor), you call a method that returns a reference to an already-created object (getInstance() or instance()). Flex won’t do that for you. However, this is not a deal-breaker. To make that class a Singleton, you just need to make sure that the constructor is only called once.

So, set up your Singleton like normal:

private static var _instance: DataModel = null;
public static function get instance(): DataModel
{
	return _instance;
}

Then, in the constructor of said Singleton, add the following:

if ( !_instance )
{
	_instance = this;
} else {
	throw new Error( "DataModel is a Singleton: only one instance allowed." );
}

All I’ve done here is move the creation of the Singleton from the get instance() method to the constructor. And if the constructor is called more than once, it throws an error. Now you can instantiate the class through MXML, just like any other component.

<model:DataModel
		id="dataModel"
		xmlURL="fileName.xml" />

Meanwhile in Actionscriptland, you can refer to this instance of your class just like it was a normal Singleton:

	trace( DataModel.instance ); // traces "[object DataModel]"

Plus, if you try to create another instance, be it through MXML or through ActionScript, you’ll get a good ol’ runtime error. You’ll have to wait until runtime to see it, but that’s certainly better than nothing, right?

Forward Kinematics in AS3

Monday, April 7th, 2008

A Confession

Kinematics in action
I must confess, firstly, that a week ago I didn’t know what forward kinematics were. Everyone seems to be talking about inverse kinematics lately (”ragdoll” physics), with no love at all for her sister forward kinematics. And really, if such a thing may be said, forward kinematics is the hot sister- I’d take her over inverse anyday.

Here’s the difference: Sometimes its desirable to model movement based on a system of interconnected objects. Your body would be such a system (your hip bone’s connected to your thigh bone, your leg bone’s connected to your calf bone, your calf bone’s connected to your foot bone, etcetera). Inverse kinematics deals with all of this starting from your foot and working inward. This would be ideal for, say, modeling you falling down the stairs or off a building- provided that you were unconscious. The motion that your foot produces during the fall is determines the angle and position of your calf, which then determines those things for your thigh.

Now forward kinematics, on the other hand, goes the other way. The reason you were unconscious in the above example is because any movement started from your body (i.e. flailing in panic as you fell off the building) would be forward kinematics- it starts from your body and moves to the end of the system. Forward kinematics is used to model more mundane things like walking. The thigh is rotated, which determines the position of the calf. The calf is rotated, which in turn determines the position of the foot. Thus, the position of the foot is determined by motion originating at the body, not the reverse.

An Example of Forward Kinematics

Okay, so that’s what forward kinematics is. And here is what it looks like (click the image to see).

AS3 Forward Kinematics

See? He really walks!

A Sponsored Link

(can’t say I wasn’t honest…)

I feel that I should also confess that I got the germ of this little engine from this book:

Foundation Actionscript 3.0 Animation: Making Things Move!

It’s by some guy named Keith Peters who apparently knows his way around the VM2. It’s not a ton of classes- two in his version, three in mine. So if you’ve got $25 and about an hour, give it a shot. And if you buy it from the link above, I get two dollars or something.

AS3 Earthquake Class v1.0

Monday, March 24th, 2008

I’ve noticed that there are a lot of small things that can save you time when designing and coding a game. Stuff that wouldn’t take long to code, but if someone’s already done it, why bother?

So in that glorious spirit of apathy, I present to you the Pixelwelders Earthquake class. This is just a simple little class that allows you to create an earthquake (or explosion, or invasion, or whatever) in your game. You just feed it a DisplayObject, the intensity of the quake, and the duration in seconds, and voilá. This is the syntax:

Earthquake.go( displayObject:DisplayObject, intensity:Number, seconds:Number ): void

And this is a two-line example:

import com.pixelwelders.fx.Earthquake;
Earthquake.go( gojira, 10, 1 );

And this is the result. Notice that each time you click, the earthquake is slightly different. Scroll down to download the class.

Download the class (and the above example) here.