Tag Archives: CS4

Tutorial: Understanding Classes in AS3 Part 2

In our first thrilling look at Understanding Classes in Actionscript 3.0, we talked about how Classes are structured, and how you can make that leap from stashing all your code in the first frame of your Flash movie like an IT chipmunk, to moving your code to its own Class.

I promised that in Part 2, we’d learn how to identify chunks of code that should be moved into their own Classes. But before we do that, it’s important to talk about what a Class is. And if you haven’t learned how to extend a MovieClip symbol in your library to write a Class around it, this tutorial is for you!

Take THAT, eggheads

Disclaimer Dear Eggheads: This tutorial is between me, a designer-turned-coder, and readers who want to learn more about Actionscript programming who likely are not Computer Science graduates. The terminology i use may not be 100% accurate, and some of the things i say may inflame your nerd rage and your unwavering demand for technical accuracy. But this article is not for you. Stop reading now. Go write some slash fiction about Captain Kirk totally doing it with the dog from Battlestar Galactica, and leave us alone to learn.

OOP: There It Is

A Class is an element of OOP – Object Oriented Programming. OOP is a flavour of coding where different objects – or things – interact with each other to solve a problem. If you’re a game programmer, the problem can be described as “How do i make a fun, functional zombie game?” The word “object” is synonymous with “Class”. You could say that Actionscript 3.0 is a Class Oriented Programming language, but the eggheads would stab you in the face.

She-Nerd

She-Nerd SMASH!!

So a Class is a thing – a chunk, a morsel, a module of code. By writing your Classes the “right” way, you’ll find you can re-use Classes from project to project. By writing them the “wrong” way, you’ll still probably wind up with a project that has nice, well-organized code that makes sense if you re-visit it a year later.

The three principles or rules to follow if you want to maximize the advantages of OOP are encapsulation, inheritance and polymorphism. We’ll be taking a brief, gentle look at inheritance in this tutorial, because i think it’s the easiest to understand when you’re starting out.

Inbred Twins

Herbert n’ Zed inherit their genes from their paw n’ their sis

Classes contain methods and properties. (Another word for “method” is “function” or “behaviour”. Another word for “property” is “field”.) A method is something a Class can do. A property is something a Class is.
Let’s explain this somewhat better by using a crappy example that a lot of OOP tutorials use. You have a Class called “Dog”. Methods of Dog – things that Dog can do – include:

  • bark
  • sniff
  • humpLeg

Properties of Dog – things that dog is – include:

  • color
  • breed
  • favouriteTreat

Another way to think of it is that methods are verbs, and properties are adjectives.

Ugly Dog

The OOP Dog example rears its ugly head

Let’s Get Real

The Dog example is almost entirely useless to us as programmers. In all my years of experience, i have never written a Dog Class. But i HAVE written my fair share of music and movie players in Flash. Let’s look at the methods and properties of a media player.

Methods of our MediaPlayer Class – things that a media player can do – include:

  • play
  • pause
  • stop
  • scrub
  • changeVolume
  • loadMedia

Properties of our MediaPlayer Class – things that a media player is, or things that describe its state – include:

  • isPaused
  • songDuration (or movieDuration)
  • isFullScreen
  • volume

Note that the method “changeVolume” probably changes the property “volume”.

Snowths

We’re gonna need a method called “turnVolumeWayWayUp”

You’re Already an Expert

The good news is that as a Flash developer, you’ve been using Classes this whole time, though you may not have known it. A MovieClip is a Class. It has methods and properties. Let’s look at some of the methods of a MovieClip – things a MovieClip can do:

  • gotoAndPlay
  • stop
  • hitTestPoint (determine whether a point is colliding with me)

And some properties of a MovieClip – things a MovieClip is (or things that describe its state):

  • x and y
  • alpha
  • rotation

Eggheads: Are you still reading this? i told you to take a hike. Don’t jump down my throat. i know that a few of these methods and properties actually belong to Classes that MovieClip inherits from, but we’re just learning, alright? Leave us alone. Go out and LARP or something.

LARP

No Pain, No Awesome

Just as you can make the leap from stowing all your code in the first frame of your movie to putting it in an .as Class file, you can (and should) make the leap from having all of your MovieClip instances “physically” present on your stage, to keeping them in the library and drawing them to the stage using code. There are many advantages to using a code-only approach which probably won’t become clear to you until you go through the excrutiating growing pains of “WHY THE HELL AM I DOING IT THIS WAY??” like i did.

Growing Pains

Growing Pains: excrutiating

So create a MovieClip in your library. NOTE: If you don’t know how to do this, you may already be in over your head. Go check out a beginner Flash tutorial and come on back.

In order for you to make the MovieClip available to you through code, you need to give it a linkage name. Here’s how:

  1. Open your Library (CTRL+L)
  2. Right-click the MovieClip symbol
  3. In Flash CS3, choose “Linkage”. In Flash CS4, choose “Propeties”.
  4. Check the box that says “Export for ActionScript”
  5. In the “Class:” field, type a logical name for your MovieClip. It’s best practice to start this name with a capital letter. Don’t use any spaces – capitalize each new word SoThatItLooksLikeThis. (This is called “Pascal case”)
  6. Click “OK”
  7. If you are a Mac user, and you’re saying “What’s a CTRL?? What’s a right mouse button?? i’m freaking OUT, man!”, go buy a PC ;)

Linkage CS3

Setting linkage for a library item in Flash CS3 …

Linkage CS4

… and in Flash CS4.

Linkage Name

Choosing a linkage name

Did you notice, before you hit OK, that there was a field labelled “Base Class:” that said “flash.display.MovieClip”? If this is your first time creating a library linkage, or if it’s old hat and you’ve never noticed this field, prepare to blow your own mind: you’ve just used the first principle of OOP – inheritance.

My Mind Done Blow’d Up

Here’s what’s going on behind the scenes. “MovieClip” is a built-in Class that the creators of Actionscript wrote. When you give your library item a linkage name, you are actually subclassing, or inheriting, from the MovieClip Class. That means that your new Class “Dog” or “MediaPlayer” or “EnemySpaceship” can now do all the stuff that a MovieClip can do. It can gotoAndPlay, it can stop, it can hitTestPoint, etc. It also inherits all of MovieClip’s properties – x and y, alpha, rotation, etc. – things that a MovieClip is, things that describe its state.

So now we’re getting to the point. When you create a library linkage like this, Flash is automagically creating a new Class (“Dog”, “MediaPlayer”, whatever). You don’t have to write it. But you CAN write it, if you want to. And since that’s what this tutorial is all about, then oh yes – we want to.

Oh Yes – Let’s

Start a new .as Class file. You can do it in the Flash IDE, you can write it with Notepad or Notepad ++ or any other text editor. i highly recommend Flash Develop. Remember our first Understanding Classes tutorial? Here’s the structure of a Class:

AS3 Class Structure

i chose these colours from Arsenio Hall’s wardrobe

So here’s what our empty Class code should look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package
{
	import flash.display.MovieClip; // Import statement(s)
 
	public class Dog extends MovieClip
	{
		// Class definition
 
		private var isBarking:Boolean; // Instance variable(s)
 
		public function Dog()
		{
			// Constructor function
			trace("i am a dog");
		}
 
		// Other functions
		private function bark():void
		{
			isBarking = true;
		}
 
		private function stopBarking():void
		{
			isBarking = false;
		}
	}
 
}

Let’s take note of a few important things.

  1. i’m calling my Class “Dog”. That’s because the linkage name in used in the Flash library was “Dog”. Note: not “dog” or “DogClip” or anything. D-o-g. Same capitalization, exact same name.
  2. And note that the linkage name can be completely different from the library symbol name. My library symbol could be called “This is a thing what i created in teh Flashs”. Doesn’t matter. Actionscript can’t “see” the library item name. It can only “see” the linkage name.
  3. Finally, remember that the Class file name has to be the same as the Class name. If our Class is called Dog, we save the file as Dog.as. Pull any other shenanigans, and you’ll get errors.

Silly dog

i SAID “no shenanigans”, DOG

i mentioned mysteriously in the last tutorial that the word “extends” is an inheritance word. When you create a linkage name in the library, Flash automagically writes a Class for you, and automagically extends (inherits from) MovieClip. Now that we’re writing the Class ourselves, nothing is automagic. We have to explicitly say that Dog (or whatever) extends (inherits from) the MovieClip Class. When this is all done correctly, Flash understands that there is a connection between the linked library Class “Dog”, and the “Dog.as” Class we just wrote.

You may or may not know the code for dynamically placing a linked library item on the stage. Here it is, using Dog as the example:

1
2
var dog:MovieClip = new Dog();  // or var dog:Dog = new Dog();
addChild(dog);

“BUT WAIT!”, you say. “I THOUGHT DOG HAD TO START WITH A CAPITAL LETTER??” Okay, first of all, stop yelling. Lower-case “dog” is the name of the variable that contains an instance (a stamp, a copy) of our master Dog Class. We could use “dog1”, “dog2”, or even “thisIsACopyOfDog”.

When you addChild(dog), you add your instance (stamp, copy) of the Dog Class to the list of things for Flash to draw to the stage (the viewable area that the player sees).

To confirm that your custom library Class is working, test your movie. You should see the trace action “i am a dog” in the Output window. (Press F2 to see the Output window – the trace action won’t appear on the stage)

What’s the Point?

You may be wondering why we went through all of this agony. The easy way is just to draw a dog and make it a MovieClip, and then leave it on the stage. There are many, many advantages to what we’ve just done. Let me list a few:

  • You can now add as many Dogs to the stage as you like dynamically. Until now, you had to add them by hand. If you needed another dog, you (the creator) had to drag one out of the library. Now you can create an “Add Dog” button. When the player presses it at run-time, your code dynamically places dogs on the stage. Now the code is doing the work, not you.
  • We’re edging closer to the next OOP principle, encapsulation. Within our Dog class, we can store methods (things that a Dog does) and properties (things that a Dog is). Every time we initialize (make a stamp or copy of) Dog, Dog can run a bunch of Dog-specific setup routines: initializeSenseOfSmell, testBarkTone, prepareToChewShoes. If you do it “right”, you’ve created a self-reliant, self-contained Class. Now every time you have a project that needs a Dog (or a MediaPlayer, an ImageGallery, a CountdownClock), you can just copy that .as Class file to a new project. If you’ve done everything “right”, it’ll just work.
  • The more you start abstracting your thinking, the more you’ll be able to write generic Classes that do a number of different jobs. You might not have another project that needs a Dog, but your generic Animal Class would still do the trick.
  • There’s a problem that Actionscript 3 introduced where you can’t always access certain pieces of MovieClips until they’re drawn to the screen. Writing a custom Class for your library elements can overcome this problem.

What’s Next?

Moving your frame code to an .as Class file was the first step. Learning how to write custom Classes for your linked library items is the next step, since it builds on (hopefully) familiar MovieClip territory and your existing knowledge. In the next tutorial, we’ll take a look at that big wad of code in your Main.as file and try to figure out which methods and properties can be logically grouped and moved into their own Classes.

For more tips, tricks and tutorials, check out our Flash and Actionscript 911 feature.

Tutorial – Fade Movie Clips in and Out Solidly

Chalk this one up to Things Jeff Taught Me. Jeff Gold (ue_jeff) is our Game Developer and, as such, is terribly helpful. It amazes me that i can use Flash professionally for ten years and i still find myself discovering features that have existed for many versions. This is one feature that Jeff tipped me off to.

Have you ever noticed when you fade a vector MovieClip in or out in Flash, that it goes all ghosty / X-ray and you can see the separate layers inside of it? This has always driven me ninety-nine percent nuts, and i’ve cooked up work-arounds that essentially flatten the artwork before i fade the clip.

Ghostbusters Logo

Bustin’ makes me feel good

Here’s what that horrendous ghosty alpha fade looks like:


[SWF]http://www.untoldentertainment.com/blog/img/2009_09_08/bloat_badFade.swf, 250, 150[/SWF]

You can totally tell that the blimple’s four legs are separate MovieClips because they fade in and out independantly of the body.

You can avoid the X-ray effect using a Blend Mode called “Layer”.

  1. Select your MovieClip
  2. Open the Properties panel
  3. In the “Blend” drop-down list, choose “Layer”

Flash Blend Mode Layer

The process is identical in Flash CS4 and Flash CS3

Now, when the clip fades in and out, it looks decent and is presentable in polite society:


[SWF]http://www.untoldentertainment.com/blog/img/2009_09_08/bloat_goodFade.swf, 250, 150[/SWF]

Cheers, Jeff!

Fancy blend modes may affect performance, so don’t go nuts with them. But if you need a clip here and there to look proper and you don’t have time for an artwork-flattening work-around, give this a shot.

To read more tutorials on Flash and Actionscript, check out our Flash and Actionscript 911 feature.

Tutorial: Understanding Classes in AS3 Part 1

A reader named Ryan (no relation) recently requested that we create a post to help him and other beginners understand Classes. So this is an ultra-gentle primer on Classes – what they are, when to use them, and how to write them. If you’re stuck in an Actionscript 2 rut, or you’re new to Actionscript 3 and it’s blowing your mind, this should help ease you in a bit better.

The path i travelled from complete code newbie to the shock-inducing AS3 god that i am today ( er … hardly) went like this:

Beginner – i put my Actionscript code everywhere – on different frames of the timeline, embedded in nested MovieClips – if i can write code on it, i do.

Spaghetti Code

That’s called “spaghetti code”, and it makes your life as a programmer difficult.

Intermediate – Scattering code through my Flash movie makes my project an enormous pain to manage and update. i’m going to put ALL of my code on the very first frame of my movie, so i only have to look in one place for it.

First Frame

Placing all your code in Frame 1 was a good idea with AS2, but you can do better

Pro – i don’t understand Classes, but i have to take the plunge somehow. i’m going to move all of my first-frame code into a separate .as Class file. i hope that’ll be the first step to breaking everything up into Classes.

Code Goes Here

This is what we’re striving for

Shock-Inducing AS3 God – Man almighty – packing an entire project’s code into one .as Class file makes it an enormous pain to manage and update. i’m going to identify little modules of code and split them off into their own .as Class files. Hey … now i’m starting to use Classes like a superstar!

God

Not *THE* God – just *A* god

The Road to Pro

In this tutorial, we’ll help you move from Intermediate to Pro by moving your first-frame code to its own Class in a separate .as file. In Part 2, we’ll take you from Pro to God by discussing ways in which you can split that enormous file up into smaller Classes, and how to figure out which pieces would make good Classes.

Many of the AS3 tutorials you see on the Internatz are written so that you can just paste the code into the first frame and compile the project. This is because it’s easier on the tutorial writers – they assume that you know how to re-write that code to put it in its own Class. But what if you don’t know?

Let’s take a piece of frame code, and bring it outside our Flash .fla file into a separate .as Class file. Here’s the frame code we’ll be using:

1
2
3
4
5
6
7
8
9
10
11
var speed:int = 5;
var ball:MovieClip = new Ball();
addChild(ball);
 
addEventListener(Event.ENTER_FRAME, moveBall);
 
function moveBall(e:Event):void
{
  ball.x += speed;
  ball.y += speed;
}

This code grabs a MovieClip called “Ball” from the library and places it on the stage. On every frame, the ball moves to the right 5 pixels and down 5 pixels. We’re going to pretend that this code exists on Frame 1 of our Flash movie. (Note: you don’t need to copy/paste this code and try it, but go ahead. If you’re not sure how to create a ball MovieClip and link it in the library, you might be in over your head already. Read up a bit on super-basic Flash stuff, and we’ll see you again shortly.)

Now let’s create an empty, external .as Class file to hold all this code. So your project will consist of two files: the Flash .fla file, which has a Ball Movieclip in the library, and a Class file with an .as extension. This isn’t anything fancy – an .as file is just a plaintext (.txt) file that you save with a .as extension. So yes, you can even write this file using Notepad or your favourite text editor.

The .fla and the .as file should exist side-by-side in the same directory.

Side by side

Same directory. We can get fancy later.

The Care and Feeding of Classes

Classes demand a particular structure:

AS3 Class Structure Diagram

Notice a few things:

  1. Package (whatever that is) wraps the whole thing
  2. the Import statements (whatever they are) come next
  3. the Class Definition (huh?) wraps everything else
  4. the Instance Variables, Constructor Function and other methods/functions are tucked inside the Class wrapper. You can put these three things in any order, but this is how you’ll usually see them in the wild.

Package

AS3 Class Structure Package Diagram

Let’s deal with that Package thing first. The Package declaration is a way of grouping all your Classes together. Let’s say you’re working on a project with Bob. You have a class called “Stuff”, and Bob has a class called “Stuff”. By uniquely naming your Package, your classes won’t conflict.

But are you working with Bob right now? Are you on a big project with multiple programmers? No. So don’t worry about it. Forget Bob – just start with a generic Package declaration, which looks like this:

1
2
3
4
package
{
     // All the other stuff goes in here, between those curly brackets
}

(note that “package” has a lower-case “p” … i’ve used an upper-case “P” in the article just to make the word pop out at you)

Import Statements

AS3 Class Structure Import Statements Diagram

Different parts of the ActionScript 3 language are already split up into packages. When you put your code on a frame in Flash, all of those packages are automatically accessible. You don’t have to do any extra work.

But when you work outside Flash, you have to tell the compiler to go grab portions of the AS3 language before you can use them. So if you say this in an .as Class file:

1
var myclip:MovieClip = new MovieClip();

the compiler will throw you an error, effectively saying “What’s a MovieClip??”

Use an Import Statement to explicitely tell the compiler that you are using a certain part of the AS3 language. This is a giant pain in the ass, and a real roadblock when you’re starting out. As a beginner, you don’t know the package names you’ll need. This is just a painstaking trial-and-error period of looking in the documentation, or referring to other people’s code, and eventually you’ll memorize this stuff. (Or you can use a program like Flash Develop, which automagically figures some of it out for you.)

So if you use a line like this later on in your code:

1
var myclip:MovieClip = new MovieClip();

you have to include an Import Statement like this at the top of the file:

1
import flash.display.MovieClip;

(note: small “i” on “import”)

It’s like you’re saying “OK, compiler – we’re going to talk about fish today. Go get that fish book out of the library so that we’re all on the same page.”

Class Definition

AS3 Class Structure Class Definition Diagram

This is where you actually start writing your Class. Here’s the format:

1
2
3
4
public class Main extends MovieClip
{
    // The Instance Variables, the Constructor Function and Methods go here
}

Let’s break down that line piece by piece:

public Class Main extends MovieClip

We don’t really need to bother with understanding public vs. private vs. protected vs. internal. Those keywords are all in the same family, but here’s what you need to know: you gotta use “public” here. Don’t worry about the other possibilities until you’ve got a handle on the basics. If you don’t use “public” in the Class that replaces your first-frame code, you’ll get an error.

public Class Main extends MovieClip

We’re writing a Class! i’m getting all tiingly.

public class Main extends MovieClip

This is the name of the Class. Feel free to use your creativity here – you can call it whatever you like. But there are a few important rules:

  1. You must use standard naming conventions. Don’t start the name with a number, and stay away from spaces and special characters.
  2. Use a capital letter to begin your Class name
  3. When you save the file, the file MUST have the same name as your Class. If your Class is called Main, save the file as Main.as. If it’s called MyProject, save the file as MyProject.as. If you don’t do this, there will be trouble.

public class Main extends MovieClip

In earlier attempts to understand Classes and Object Oriented Programming (OOP), you may have heard of the concept of “inheritance.” That’s what the “extends” keyword is all about. Without exploring too deeply, we need to extend / subclass / inherit from an ActionScript 3 Class called MovieClip. Why? Because if we don’t, we’ll get yelled at. So just do it. Strive to understand it later.

public class Main extends MovieClip

That’s the Class we’re inheriting from. It’s like saying “my Class called Main can do everything a MovieClip can do, and more.”

Instance Variables

AS3 Class Structure Instance Variables Diagram

Instance Variables, sometimes called Fields, are variables that you need to access throughout your Class. If you’re familiar with the idea of scope, you’ll know that when we do this:

1
2
3
4
function myFirstFunction():void
{
   var myVariable:String = "someValue";
}

we’ll get an error if we try doing this:

1
2
3
4
function mySecondFunction():void
{
   trace(myVariable);
}

That’s because myVariable is scoped to myFirstFunction. It doesn’t exist outside that function.

If you want variables to be accessible to all the different functions in your Class, you declare them in the orange area on the diagram. You’ll also need to decide whether you’re making these variables public, private, internal, protected, etc. This is not a decision you need to make when all your code is on the first frame. OOP purists would absolutely FREAK OUT if they were reading this, but i’m going to recommend you make all your variables public for now. It’s the least error-prone approach when you’re learning, and when you know more, you can get a little fancier.

So here’s what a typical Instance Variable would look like at this point in the .as Class file:

1
public var myVariable:String;

Notice that we’re not even setting a value yet. We can, but we don’t have to. We’re just reserving a spot in the computer’s memory for this variable so that the whole Class can use it.

The Constructor Function

AS3 Class Structure Constructor Function Diagram

This Main Class will be what’s called the “point of entry” into our Flash program. It’s the first place where code will start being activated. A Constructor Function is like the point of entry in any Class. It’s the first function that’s fired when a Class is encountered by the interpreter.

Here’s what our Constructor Function should look like:

1
2
3
4
public function Main()
{
 
}

As with Classes, you have to follow a few rules with your Constructor Function:

  1. The Highlander rule: “there can be only one”. i believe other languages allow you to have multiple Constructor Functions, but AS3 does not.
  2. The name of the Constructor function must be the same as the name of the Class.
  3. Make sure it’s public.
  4. Don’t return a value – not even “void”. Constructor Functions are not allowed to return a value.

Putting It All Together

Let’s slap it all together and see what we’ve got:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package
{
    import flash.display.MovieClip;
    public class Main extends MovieClip
    {
        // instance variables go here
 
        public function Main()
        {
             trace("It works!");
        }  
 
        // other functions can go here
    }
}

Super! We’ve got the shell of a Class that we can use as our point of entry. (Make sure it’s saved as “Main.as”, or whatever you called your Class.) We’re just missing one step. We have to tell Flash that instead of looking to the first frame of the movie as our point of entry, we want it to look at the “Main” Class.

Open up the Properties panel in Flash and look for an empty field labelled “Document class:” (CS3) or “Class:” (CS4).

Document Class Flash CS3

This is what it looks like in Flash CS3

Document Class Flash CS4

… and in CS4

Note: you won’t be able to use this feature unless you’re targeting Flash Player 9 or above, with ActionScript 3 or above.

Type “Main” (without the quotes) into this field. Then save and compile. You should see the trace statement “It works!” in the Ouput panel.

All the Rest

Now that we have Flash looking to an external .as file to get the party started, let’s port over some of that first-frame code into our class. i’ll paste the clean version first, and then an identical copy with extensive comments so that you can follow along at home:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package
{
    import flash.display.MovieClip;
    import flash.events.Event;
 
    public class Main extends MovieClip
    {
        public var ball:MovieClip;
 
        public function Main()
        {
             ball = new Ball();
             addChild(ball);
             ball.speed = 5;
 
             addEventListener(Event.ENTER_FRAME, moveBall);
        }
 
        public function moveBall(e:Event):void
        {
                ball.x += ball.speed;
                ball.y += ball.speed;
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package
{
    // This is the commented version.
    import flash.display.MovieClip; // since both Ball and Main are MovieClips,
              // we have to import the MovieClip Class 
    import flash.events.Event; // Later on, we use the Event Class, so
             // we need to import it here.
 
    public class Main extends MovieClip
    {
        // See how the Class definition and import statements
        // are inside the package curly brackets?
 
        public var ball:MovieClip; // We declare "ball" up here
             // so that the whole Class can refer to it
 
        public function Main()
        {
             // This is the constructor function!
 
             ball = new Ball(); // Since we already declared "ball"
               // as an instance variable, we can just refer to it
               // directly without redefining it
             addChild(ball); // Where does ball get added?  Main
               // is representing our Flash movie's main timeline,
               // so that's where the ball appears
             ball.speed = 5;
 
             addEventListener(Event.ENTER_FRAME, moveBall);
             // note: no need for the word "this", in case you
             // were wondering
        }
 
        public function moveBall(e:Event):void
        {
                ball.x += ball.speed;
                ball.y += ball.speed;
                // Again, because "ball" was defined up top, 
                // the moveBall method can refer to it
        }
    }
}

Are You Smart Yet?

Hopefully, you know enough now to port your whole wad of first-frame code to a separate .as Class file. That’s a baby step towards actually using the power of Classes to save yourself time in the future, and to keep your code organized, updatable, and a pleasure to re-visit.

In the next part of this tutorial, we’ll look at ways you can pick through your Wall of Code and identify which pieces you can could out into their own Class files.

For more Flash AS3 Tutorials and a pile of other useful stuff, check out our Flash and Actionscript 911 feature.

Flash CS4 3D – Depth Management

i’ve been playing around with the 3D tools in Flash 10/CS4, with half a mind to completely redo our cube-mapped memory game Two By Two with an actual 3D cube. (Currently, the game uses a series of skewed planes to fake the 3D effect.)

The good news is that CS4 does support 3D, although some people on the web are calling it 2.5D for one particular reason: the DisplayObjects that you transform and translate are unaware of each other, and do not exist in the same 3D space.

Here’s what that means: you can have two planes sitting next to each other. Depth-wise, PlaneA is in front of PlaneB. You move PlaneA backwards along the z axis, and it never swaps depths behind PlaneB. It’s as if the two clips are entirely autonomous and exist in their own little 3D worlds. Which they do.

note: you’ll need to be running the Flash Player 10 plugin to view these examples. Get it HERE.

 
[SWF]http://www.untoldentertainment.com/blog/labs/3d/depthProblem/depthProblem.swf, 550, 400[/SWF]
 

This becomes a big problem when you need things to look natural. Check out this Flash coder’s experiment with a 3D world and a camera:

Flash 3D World with Messed Up Depth

This is fine if all of your game characters have X-Ray vision, i suppose.

The floors and the walls are placed correctly, but they all show through each other. i had the exact same problem when i tried building a cube from MovieClips. Placing the clips was very easy, but the depth problem baffled me. i knew that i had to loop through all the cube faces and re-order them based on their z properties, but i didn’t know how to do that, since localToGlobal only supports x/y coordinates.

It turns out you have to actually write your own depth manager if you want to build any kind of 3D object and have it display correctly. i found just the code i needed here on Drew Cummins’s blog:

http://blog.generalrelativity.org/?p=28

i’m a big enough man to admit that at one o’clock in the morning last night, i didn’t fully grasp how this code did what it did. Happily, it worked. You can see the difference in cube rendering below. The cube on the left applies Drew’s depth management routine.

Thanks, Drew!

 
[SWF]http://www.untoldentertainment.com/blog/labs/3d/cube_depthManagement/cube_comparison.swf, 550, 400[/SWF]
 

Additional notes: there is a (possibly deliberate?) type-o in Drew’s code. One of the loops is missing a minus operator on its iteration decrementor (i-), so watch out for that.

You may also have to rely on the ADDED_TO_STAGE event, as Drew’s code threw me an error when doc.stage was null. This can happen when you try to fire code before an object actually exists on the stage.