Monday, September 5, 2011

Flash FAQ: Communicating between Classes in AS3

I often answer questions on the forums over at Actionscript.org and I noticed that people are always asking about communicating between classes. In particular, people ask how you can change a variable in the document class (main class) from another class. So instead of repeating myself, I'll post it here.

Short answer:  MovieClip.(this.parent).variable=xxx;

Long Answer:

You have to be careful when you access variables in one class from another class. Things can get confusing pretty quickly. But a good example of when it is kosher is when you have an enemy in a game; when it is hit by a bullet, it tells the document class to increase the score. It's simple and foolproof enough.

Okay, I set up a flash document with Main.as as the document class. I declare an object obj which is an instance of the class Obj. I declare a variable pvar, which we will set to 1 and then set to 2 by running a function in Obj.as:


package  {

import flash.display.MovieClip;


public class Main extends MovieClip {

public var obj:Obj;
public var pvar:int;


public function Main() {
pvar=1;
obj = new Obj;addChild(obj);
obj.ResetVar();
trace(pvar);
}//game
}

}


Can you see that? It's easy to run a function on a separate class... we just say obj.ResetVar();


Of course, we haven't created Obj.as yet, so let's do that now:


package {
import flash.display.MovieClip;
public class Obj extends MovieClip {


public function Obj() {}//Obj


public function ResetVar(){
MovieClip(this.parent).pvar=2;
}//rv


}
}


Now you can see how we use the line MovieClip(this.parent).pvar=2; to refer to the parent of this movie clip and set pvar to 2.

Try it and you should get the trace '2'.

Got it? Good.

If you have any questions or the explanation isn't clear, please feel free to leave a comment. If you're looking for some more Flash tutorials or projects, try here: flashbynight.com/tutes

Sunday, September 4, 2011

Things Fall Down

Time for a new Flash game and I hope you like it.

In Things Fall Down, the sky is falling and everything else along with it. Keep jumping up and keep yourself above ground.

There are fifteen short levels that would probably take around one hour to finish.

The game is at: http://www.flashbynight.com/thingsfalldown

Have a look at some screenshots here:



If you've played some of my games before, you'll recognise the graphical style. Enjoy!