Hey, posting here random tips for people who have worked with Flash before and might be struggling to get AS3 work with F9 (currently using F9 AS3 preview alpha). Notice that Flex is completely different program and things work different ways.
Printable View
Hey, posting here random tips for people who have worked with Flash before and might be struggling to get AS3 work with F9 (currently using F9 AS3 preview alpha). Notice that Flex is completely different program and things work different ways.
Trying to make sample sprite and adding key listener to it so it will detect keys being up and down:
This, however, does not trace abything. Why? Because the new sprite has no focus and only item with focus will detect keys. So, instead you could add listeners to the stage:PHP Code://make new sprite
var spr:Sprite = new Sprite();
//add listeners
spr.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
spr.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
//functions to trace keys
function keyDownHandler(event:KeyboardEvent):void {
trace("keyDownHandler: " + event.keyCode);
}
function keyUpHandler(event:KeyboardEvent):void {
trace("keyUpHandler: " + event.keyCode);
}
Stage has focus by default so it detects the keys. You could also add listeners to sprite, but then you have to make sprite to have focus:PHP Code:stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
This will detect keys as long sprite does not lose focus (user could click on text field for example).PHP Code:stage.focus = spr;
spr.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
spr.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
In earlier versions you could have movie clips attached by giving them linkage name and then using code like:
AS3 does not allow this anymore. First you need to add class to your movie clip. Right click on mc in library and choose Properties. If you only see small pop-up with name and type, click on Advanced button. Make sure you have checked "Export for Actionscript". Type the name in name field, for example "myMC". Type the same name into class field too. Flash should give warning message "A definition for this class could not be found on disk so one will be automatically generated upon export". Click OK. Class field should now read "myMC (Auto-generated)". Click OK to close panel. Now your movie clip will be exported and class is created for it inside swf.PHP Code:this.attachMovie("linkagename", "newmcname", 1);
To add this movie clip on stage you first have to create new instance of that class:
This will make a new movie clip from yours, but it wont be added on stage. You have to use addChild to make it visible:PHP Code:var newMC=new myMC();
PHP Code://position
newMC.x=200;
newMC.y=300;
//add to stage
this.addChild(newMC);
You could use any number for depth when attaching movie clips in earlier Flash:
Depths 0-99 were unused and you could add other items in those depths later when needed. Also, if you added new item into depth already having an item, previous item was replaced by new item:PHP Code:this.attachMovie("linkagename", "mc", 100);
Not in Flash9. In Flash 9 you can only add items in depths equal or less to current number of children. If container does not have any children, this will add new one:PHP Code:this.attachMovie("linkagename", "mc1", 100);
//replace mc1 with mc2
this.attachMovie("linkagename", "mc2", 100);
However, this will result in error:PHP Code:container.addChildAt(mc, 0);
If you try to add new item in depth where already some children exists, it is not replaced anymore, all children starting from that depth have their depth increased by 1.PHP Code:container.addChildAt(mc, 10);
Lets say container has 3 children: mc0, mc1 and mc2 in depths 0, 1 and 2. If you now add new mc in depth 1
you end up with 4 children: mc0 (depth0), mc3 (depth1), mc1 (depth2) and mc2 (depth3).PHP Code:container.addChildAt(mc3, 1);
Same way, if you use removeChildAt method to remove child from certain depth, all other chidren are moved down by 1. Using same container with 4 children
will result container having 3 chidren: mc0, mc1 and mc2 in depths 0, 1 and 2.PHP Code:container.removeChildAt(1);
In AS 1/2.0 you attached a movie clip by specifying the linkage id, like this:
This made it easy to attach a movie clip with a linkage id that is calculated ("myMC"+n). But since you now need to create a new instance of the asset, it gets a bit more cumbersome if you want to do it by specifying a string in AS 3.0:Code:var n = 1;
this.attachMovie("myMC"+n, "mc", 100);
In this case "myMC1" is a movie clip in the library. So, the code above is equal to:Code:import flash.utils.*;
var n:int = 1;
var id:String = "myMC"+n.toString();
var AssetClass:Class = getDefinitionByName(id) as Class;
var newMC:MovieClip = new AssetClass();
Code:var newMC:MovieClip = new myMC1();
Excellent thread T ( And Strille ), long overdue.
Come them coming :)
Squize.
PS. Be nice to hear from people using Flex as well. I've read that you can't have FDT and Flex running in the same copy of Eclipse. Knowing things like that for definite would be a huge help for people wanting to move to as3.
In AS2 you could take a piece of a XML object and put it inside a array and loop in that array.In AS3 however this will not work, instead you have to use an obejct called XMLLists, that can be many XML objects or just a piece of one
Example, this is the game.xml:
<game>
<level>
<something>3</something>
<something>4</something>
<something>8</something>
</level>
<level>
</level>
</game>
you go
length is a method, not a property like it is in arrays, so use it like this: length();Code:var soms:XMLList = new XMLList();
soms = gameXML.level[0].something ;
trace(soms[0]);//3
trace(soms[2]);//8
trace(soms.length());//3;
var i:int = soms.length();
while(i--){
trace("soms["+i+"] = "+soms[i]);
}
Excellent, excellent, excellent! I haven't even looked at as3 yet but basic tips like these will go a long way in helping when I do finally decide to 'get with the times'. Bookmarking this thread :)
I particularly like what I'm hearing in regards to how depth sorting is handled now. It should make it a lot easier to create a pseudo z-sorting technique (I sure do like the easy way out ;) ). I'm curious though, because you don't mention anything about it, are you able to switch depths of a child once it's already created? Say I wanted to take the child on that's on the very top depth and move it to the bottom, is it as simple as giving it the lowest depth and letting flash sort of the rest?
Yes. AS3 provides much more methods to control depth:Quote:
Originally Posted by DancingOctopus
addChild - adds child to next avaialable depth
addChildAt - adds child to certain depth (moving other children up)
getChildAt - returns child at specific depth
getChildByName - returns child with specific name
getChildIndex - returns depth of child
removeChild - removes child
removeChildAt - removes child from specific depth
setChildIndex - changes depth of child
swapChildren - swaps depths of 2 children
swapChildrenAt - swaps depths of 2 children at specific depths
Excellent news.
I'm still apprehensive of the lack of movieclip and identifiers. My entire game structure consists of library items with identifiers and classes that extend the movieclip class. There's always another solution though I guess :)
In AS3 items have different default values (some are similar to AS1/2):
*variable without type description has default value of undefined
*variable with set type has default value of null
*booleans have default value false
*integers have default value 0
*numbers have default value NaN
The conversion from undefined to null is automaticPHP Code://declare variable without type
var var1;
//declare new object
var var2:Object;
if(var1==undefined){
trace("var1 is undefined");
}
if(var2==null){
trace("var2 is null");
}
However, variable with type can not be converted into undefined value, this will result in warning:PHP Code:var var1;
if(var1==null){
trace("var1 is not really null, but it is converted to null when compared");
}
For booleans null is also not allowed, this will result in warning again:PHP Code:if(var2==undefined){
trace("var2 is undefined");
}
For string, default value is null. Notice that it is not same as empty string (""):PHP Code:var var3:Boolean;
if(var3==null){
trace("var3 is null");
}
var1 will only trace as null and var2 will only trace as empty string. If you try to trace empty string itself trace(var2), your trace of course shows nothing.PHP Code:var var1:String;
if(var1==null){
trace("var1 is null");
}
if(var1==""){
trace("var1 is empty string");
}
var var2:String="";
if(var2==null){
trace("var2 is null");
}
if(var2==""){
trace("var2 is empty string");
}
Integers are 0 by default:
but numbers have value of NaN which is not same as 0. This does not trace anything:PHP Code:var var1:int;
if(var1==0){
trace("var1 is "+var1);
}
Use isNaN function to check if number has no value:PHP Code:var var2:Number;
if(var2==0){
trace("var2 is "+var2);
}
"Not a number" results also from dividing 0 by 0 and taking square root from negative number:PHP Code:if(isNaN(var2)==true){
trace("var2 is "+var2);
}
Notice that result from dividing number by 0 is Infinity or -Infinity:PHP Code:var var1=0;
var var2=0;
trace(var1/var2);
var var3=-1;
trace(Math.sqrt(var3));
PHP Code:var var1=1;
var var2=-1;
var var3=0;
trace(var1/var3);
trace(var2/var3);
Once you have declared a variable with certain type, you can not change its type later. This example traces both values because myVar1 has no type and can be both number and string:
However this example traces NaN because variable is Number and the string is converted into number (which results in NaN in this case):PHP Code:var myVar1=9;
trace(myVar1);
myVar1="ab";
trace(myVar1);
If you try to change type later you get error message:PHP Code:var myVar2:Number=9;
myVar2="ab";
trace(myVar2);
myVar3 is first assigned to untype, changing it later to string is not allowed. Same way you can not use var keyword again. This gives error again:PHP Code:var myVar3=9;
myVar3:String="ab";
trace(myVar3);
In main timeline you can use this keyword or not, both ways you access to same variable. This traces 3:PHP Code:var myVar4=9;
var myVar4=10;
But things can get complicated when variable with same name is used inside the function. This traces 2, variable is accessible in the function too:PHP Code:var myVar4=1;
this.myVar4++;
myVar4++;
But trying this is different:PHP Code:var myVar5=1;
function doStuff() {
this.myVar5++;
}
doStuff();
trace(myVar5);
Here we have 2 separate variables, one is available only inside the function and other is available both in the function and outside. The linePHP Code:var myVar5=1;
function doStuff() {
var myVar5=10;
myVar5+=10;
this.myVar5++;
trace(myVar5);
}
doStuff();
trace(myVar5);
uses variable in the function, but using "this" keyword ignores new variable in the function and uses one declared outside.PHP Code:myVar5+=10;
Wow, thanks for the great tips tony, strille and Cimmerian. They should prove most usefully when I finally go over to CS3.
Bookmarked! Just like to say thank you.
just want to add this link which i consult regularly when using AS3, best resource I've found out there
http://www.kirupa.com/forum/showthre...&highlight=AS3
it also deals with Z sorting techniques.
Cheers Tony, will be coming back to this thread when I get AS3.
Will this stuff be on your site or do I need to bookmark it?
Dont plan to put this on my site, I will add link to this thread into Knowledgebase sticky so you can find it from there.Quote:
Originally Posted by EvilKris
Yes, its great resource. I am hoping to gather here tips that are useful when making games, also things that have been changed/added in AS3/F9 compared to older versions and mostly about Flash9 excluding Flex (sorry, Squize, but Flex is completely different program and very hard for me to understand even the simplest steps in it).Quote:
Originally Posted by mr_malee
In Flash9 you can check if your game has lost focus. Whether user has clicked outside or opened another tab or switched to other program.
Lets say your game has main function moveAll which runs everything:
You can now use Deactivate event to remove listener to main function and Activate event to re-add it:PHP Code:stage.addEventListener(Event.ENTER_FRAME, moveAll);
Flash9 also has event to detect when mouse cursor leaves your game stage:PHP Code:stage.addEventListener(Event.ACTIVATE, goagain);
stage.addEventListener(Event.DEACTIVATE, stopit);
function goagain( event:Event ) : void{
stage.addEventListener(Event.ENTER_FRAME, moveAll);
}
function stopit( event:Event ) : void{
stage.removeEventListener(Event.ENTER_FRAME, moveAll);
}
Notice that cursor leaving game stage does not make game to lose focus, these are separate events. Cursor may be outside of your game stage, but your game can still detect keyboard events.PHP Code:stage.addEventListener(Event.MOUSE_LEAVE, stopit);
Also, if you do detect mouse leaving stage, dont forget to check when mouse arrives back, there is no special event for mouse appearing over stage again. You could use mouseMove event for that as mouseMove is only detected when mouse cursor is over display object.
XMl; work with xml now is so much better cos is much more intuitive,
in AS2 in an xml object like this
<machines>
<cars> 3 </cars>
<planes> 5 </planes>
<computas> 2 </computas>
<warriors>300</warriors>
</machines>
machines would be the firstChild, and cars the firstChild.firstChild
Now you send all this to the hell cos the biggest node (like machines)will be the main object in wich others area propertys
Using the previous example you could acess it like this
var mach:XML = new XML =
<machines>
<cars> 3 </cars>
<planes> 5 </planes>
<computas> 2 </computas>
<warriors>300</warriors>
</machines>;
trace(mach.cars);// 3
The same if were text nodes
<cars>ferraris</cars>
would output ferraris
And if you have many <> with the same name inside they will be like propertys of an array
<machines>
<car>ferrari</car>
<car>mitsubishi</car>
<car>blablabla</car>
<planes>...(all the rest the same)
trace(mach.car[1]);//mitsubishi
Now, i dont like attributes but if you do like, to acess them is just a matter of using a .@
<machines>
<car status ="ok">ferrari</car>
<car status = "ok">mitsubishi</car>
<car status = "broken">blablabla</car>
trace(mach.car[1].@status);//ok
I dont like it cos its seems non intuitive, dont need it for each child to think of themselves as a property
Now, you have your xml, many childs has many caracteristics, lets supose you want the child wich status == "broken", or
the one wich color is red,you dont need to loop the entire XML looking for it
trace(mach.car.(@status == "broken"));
trace("red = "+mach.car.(color == "red"));
Both will return a XMLList with the entire node, i mean,
<car status="broken">
blablabla
<color>invisible</color>
</car
and
<car status="ok">
mitsubishi
<color>red</color>
</car>
If there was more them one child that is what you want,as if your search was
trace(mach.car.(@status == "ok"));
it will return a XMLList object made of those nodes,so you can create many XMLLists dynamically with only the pieces you want,
This has many uses, more than i can think of it now
If you dont want the entire child but just a piece of it, for example in
<car status ="ok">ferrari
<color>blue</color>
<owner>thisguy</owner>
</car>
<car status = "ok">mitsubishi
<color>red</color>
<owner>james bond</owner>
</car>
<car status = "broken">blablabla
<color>invisible</color>
<owner>leprechaun</owner>
</car>
You put what you want in the end of your search
trace(mach.car.(color == "red").owner);//james bond
If more than one result appear it will return a XMLList made just by those results
trace(mach.car.(@status == "ok").owner);
//<owner>thisguy</owner>
<owner>james bond</owner>
Next, how to edit XML
The same way you acess you can edit
mach.car[1].owner = "pierce brosnan";
trace(mach.car.(color == "red").owner);//pierce brosnan
To delete a child:
delete mach.car[2] ;
You can also just throw a bunch of propertys inside it
var pr:XML = <lala></lala>;
pr.gegege = "i am the leprechaun";
pr.daaaaaaaaa = "jskhkshflaf";
will be:
<lala>
<gegege>i am the leprechaun</gegege>
<daaaaaaaaa>jskhkshflaf</daaaaaaaaa>
</lala>
And also put things inside the things you just put inside(this whole put inside things is really nuts)
pr.gegege.name = "im not a person i am a doctor";
<lala>
<gegege>
i am the leprechaun
<name>im not a person i am a doctor</name>
</gegege>
<daaaaaaaaa>jskhkshflaf</daaaaaaaaa>
</lala>
If you want to change the name of a child:
pr.setName("pleasure");
trace(pr);
<pleasure>
<gegege>
i am the leprechaun
<name>im not a person i am a doctor</name>
</gegege>
<daaaaaaaaa>jskhkshflaf</daaaaaaaaa>
</pleasure>
and with a child of a child
pr.gegege.setName("gess");
<pleasure>
<gess>
i am the leprechaun
<name>im not a person i am a doctor</name>
</gess>
<daaaaaaaaa>jskhkshflaf</daaaaaaaaa>
</pleasure>
If you want to put a chilc inside your XML,but in the last place,just use appendChild:
var deaths:XML =
<deaths>
</deaths>;
var hell:XML = <hell> hello </hell>;
var world:XML = <holl> world </holl>;
deaths.appendChild(hell);
deaths.appendChild(world);
trace(deaths);
/*output:
<deaths>
<hell>hello</hell>
<holl>world</holl>
</deaths>
*/
Be aware that this stuff will only work on lists that have just one node, i mean, if you try
deaths.hell.appendChild(<something>hell</something>);
it will not work because there are many hell nodes.Nodes as hell.
And also there is prependChild, prependChild does the same,but put on the beginning
deaths.prependChild(<hell>bye cruel world</hell>);
<deaths>
<hell>bye cruel world</hell>
<hell>hello</hell>
<holl>world</holl>
</deaths>
Now, if you want to put a node somewhere in the middle of other nodes you can use insertChildBefore and insertChildAfter
var moreHell:XML=
<brell>hellhellhellhell</brell>;
deaths.insertChildBefore(deaths.hell[1] , moreHell);
It will insert moreHell before deaths.hell[1]
it will be:
<deaths>
<hell>bye cruel world</hell>
<brell>hellhellhellhell</brell>
<hell>hello</hell>
<holl>world</holl>
</deaths>
The same to insertChildAfter, just that is after...pretty obvious, isnt it?
And finally, how to replace nodes with replace()
His first parameter goal is to identify the child you want to replace, the second is what you want to put in his place
The first one can be the index of the child, or a string wich is the stuff inside the <>
deaths.replace(0, <hell> zirou</hell>);
It will replace death[0] ( <hell>bye cruel world</hell> )and put <hell> zirou</hell> in his place
<deaths>
<hell>zirou</hell>
<brell>hellhellhellhell</brell>
<hell>hello</hell>
<holl>world</holl>
</deaths>
If instead of the index you give it the string,and there is more than one child for it, all of them will be removed and
just one <hell>bye cruel world</hell> will be in his place
<deaths>
<hell>zirou</hell>
<brell>hellhellhellhell</brell>
<holl>world</holl>
</deaths>
And now hasComplexContent and hasSimpleContent; those two can be usefull when you are looping a XMLList and want to know
what your child has
To flash, simple content are things like attributes, texts, comments and complexContent are another childs
trace("simple? "+deaths.hell.hasSimpleContent())//simple? true
deaths.brell.somethingmore = "lovelovelove";
trace("complex? "+deaths.brell.hasComplexContent())//complex? true
True, cos now brell is a happy parent with a somethingmore child
<deaths>
<hell>zirou</hell>
<brell>
hellhellhellhell
<somethingmore>lovelovelove</somethingmore>
</brell>
<holl>world</holl>
</deaths>
I hope you can have something done with this, enjoy!
"sorry, Squize, but Flex is completely different program"
Not a problem mate, it's more than enough what's already here ( And the whole FDT / Eclipse thing is a mare to set up as it is, I imagine Flex isn't any easier ).
Although if anyone does know how to do it, don't be shy in coming forward and sharing :)
( After not coding in the Flash IDE for a fair few months now I really couldn't go back to using it again ).
Squize.
If people are looking to get up and running with AS3 but don't have the editor, you can use FlashDevelop from www.flashdevelop.org and follow the directions on that site to use the flex2 sdk to handle compiling. If you are doing things 100% in code, it works great.
Whats the problem with f9 public alpha?
Once you're used to a dev system like FDT it's really impossible to go back to the standard IDE. Simple as that really.
Squize.
Change it inside a TextFormat object and give it to the TextField object
I mean,once you have your TextFiel
create your TextFormatCode:vat te:TextField = new TextField();
and put it in the defaultTextFormat property of your TextFieldCode:var fo:TextFormat = new TextFormat();
fo.font = "Arial";
fo.size = 15;
You can change other things like color, bold, italicCode:te.defaultTextFormat = fo;
te.text = "blablabla";
addChild(te);
italic and bold are just boolean stuff, give it a true if you want to use it
There are other things you can do with TextFormat, like create links, but they are not much game related, i thinkCode:fo.bold = true;
fo.italic = true;
fo.color = 0xFF0000;
This is an old fps counter that someone here mades in AS1/2 whatever, and i have tried to convert it in AS3, i bet it can be improved, since i dont understand completely how it works
Anyway, using it may save you some minutes in your life
usage:
var fp:fpsCounter = new fpsCounter(this);
addChild(fp);
Obs:this (this) is for it to have a reference to what was called "_root"
There are better ways for it to have it,i just dont use cos f9 public alpha dont have it
Code:
package{
import flash.display.Sprite;
import flash.text.TextField;
import flash.events.Event;
class fpsCounter extends Sprite{
var rr:Object;
var FPS:TextField;
var my_date:Date;
var startTime: Number;
var currTime:Number;
var elapsedTime:Number;
var count:Number;
function fpsCounter(rut){
rr = rut;
rr.addEventListener("enterFrame", this.oef);
FPS = new TextField();
addChild(FPS);
my_date = new Date();
startTime = my_date.time;
currTime = 0;
elapsedTime = 0;
count = 0;
}
function oef(ev:Event){
my_date = new Date();
currTime = my_date.time;
elapsedTime = currTime - startTime;
count ++;
if (elapsedTime>1000) {
FPS.text = count.toString();
count = 0;
}
if (elapsedTime>1000) {
my_date = new Date();
startTime = my_date.time;
}
if (FPS == NaN) {
FPS = 0;
}
}
}
}
Cool thread! Here's a nice little new thing in AS3 - labels.
code:
myLabel: for ( int j = 0; j < 30; j ++ )
{
for ( int i = 0; i < 30; i ++ )
{
if ( condition ) break myLabel;
}
}
It's not really that useful, but I think it's elegant. Works on
any code block.
I'm surprised "for each.." isn't covered yet. Really useful.
code:
var asd:Array = [ "one", "two", "three" ];
for ( var i in asd )
trace ( asd[i] );
for each ( var j in asd )
trace ( j ); // will trace same as above
It might be worth noting that the private namespace is now truly private, subclasses won't be able to access it. protected is the equivalent of (AS2)private. When making your own classes for MCs in the library (or making your document class!) be sure to make them public! That one took me a while to figure out.. :/
I wonder if this thread will not become a copy and paste things from the as3 forum
for each vs for in, for example, is already covered in the senocular's tips of the day
In AS2 to change something in a MovieClip that is inside other clip you have to type his whole scope like
In AS3, however,you can change it no matter where he is in the display listCode:_root.MasterClip.blasterClip._x = 10;
Code:
var sp1:Sprite = new Sprite();
addChild(sp1);
var sp2:Sprite = new Sprite();
addChild(sp2);
var mc:MovieClip = new MovieClip();
mc.x = 10;
sp1.addChild(mc);
trace(mc.x);//10
sp1.removeChild(mc);
sp2.addChild(mc);
trace(mc.x);//10
In AS2, with this [] you can create objects dynamicaly, using for example, a String or a Number to define him.In AS3 you also can, but dont forget to put the scope behind of the []
Or, if you already have them created in the normal way, and a string should tell you wich one to use,you also can:Code:var someString:String = "cat";
this[someString] = new Object();
this[someString].zp = 10;
trace(this[someString].zp);//10
trace(this.cat.zp)//10
However, those things are very slow, if you can use simple Arrays insteadCode:this[tellerString].x = 10;
@ Cimmerian: in previous AS languages one could easily create a shortcut like:
same can be done with as3 but slightly different:Code:_root.MasterClip.blasterClip._x = 10;
bc = _root.MasterClip.blasterClip;
bc._x+=10;
trace("x: "+bc._x);//outputs 20
Code:var container:Sprite = new Sprite();
addChild(container);
var sprite:Sprite = new Sprite();
var sprite.name = "id_1";
container.addChild(sprite);
//now create a linkage
var winInstance:Sprite = container.getChildByName("id_1");
winInstance.x = 20;
True, but this is creating another object wich is another reference to the same space in the memory
humm...you edited after i posted...those are not the same things,however
this
Is creating another object wich is another reference for the same objectCode:_root.MasterClip.blasterClip._x = 10;
bc = _root.MasterClip.blasterClip;
bc._x+=10;
trace("x: "+bc._x);//outputs 20
And this
Is returning another reference too, but will only work if the sprite was already a child of container,this way also it will not work anymore when you change his parent, for exampleCode:var container:Sprite = new Sprite();
addChild(container);
var sprite:Sprite = new Sprite();
var sprite.name = "id_1";
container.addChild(sprite);
//now create a linkage
var winInstance:Sprite = container.getChildByName("id_1");
winInstance.x = 20;
My previous point was that in AS3 you dont need references or parents to do this.I mean, to use getChildByName you have to know who is the parent, for dynamic content not always you will know it and sometimes it will not have any parent at all
Thats when you simply go
blaster.x = 20;
Without need to worry with references or parents
how to make your classes have acess to the former '_root'
Two ways to do this:
First one,( wich i will not use anymore)is pass a reference to
the stage when you create it or later
like
var something:so = new so(this);
or
something.stageReference = this;
When you declare something in the stage
Inside your class you have some object that will store that reference
I will not use this anymore, this was a dirty cheap quick fix that messes
with the constructor function and mess with everything and i dont like it
Now, another way is to use the Event
ADDED
This event is dispatched when a displayObjects adds something to his displayList
So, inside the stage you can put a function like this
ev.target is the object added.Code:stage.addEventListener("added", addedHandler);
function addedHandler(ev){
ev.target.onAddedToStage();
}
And what it will do is to call a function onAddedToStage on a child
whenever any child is added
From the moment it is addChilded, your child class knows who is his .parent ,
Inside your child you will have to have this function,in wich you
do anything you want to do with your stage reference
There are other ways to do this, there is also an event onAddedToStageCode:function onAddedToStage(){
stageReference = this.parent;
//and you do what you want with it
stageReference.addEventListener("enterFrame", onEnterFrame);
}
wich not work in the f9 alpha, senocular also made a class to let your
childs know when they are added to anything...many ways
its important to use the correct number types ot achieve best performance.
The different number types are:
int
Number
uint
int - a 32-bit signed integer, or how i like to put it (numbers without decimals :)) they are good for loops, addition and subtraction and are faster than Number in these situations
Number - IEEE-754 double-precision floating-point number (number with decimals) it almost has the same speed as int in the loop, addition and subtraction department, but its much faster with multiplication and division because no conversion is required between the data types
uint - 32-bit unsigned integer, or positive whole Number. It is the slowest number type. I haven't found a good purpose for it yet. Adobe says that its good for ARGB and RGB color values, so i guess it is :)
so the two most common data types you'll probably use are Number and int when dealing with the mathematics in your games.
int is great for loops, addition and subtraction and bit shifting i.e >>, << because it deals with whole numbers. When the number can become a decimal/fraction it is automatically converted to the Number data type to deal with the operation. Then its converted back to int. Division and multiplication should be avoided also because the results will probably result in a fraction.
Number is the all-rounder, it performs well in all situations so should be used if you're unsure of what type to use.Code:var n:int = 4
var i:int = 1
//fast
n++
//slow
i += .1
i += .6
i += .4
i += .3
trace(n, i) //5, 1
So don't assume that because int doesn't require as much power to process than Number does that it will speed up any project, because little conversions can happen all over the place and might slow it down more than if you just used Number. Also remember than int will remove any decimal points in a Number, so realistic physics should always use the Number type, unless you are after unnatural movement.
hope it helps.
I would like to know how to use those << >>Quote:
Originally Posted by mr_malee
This killing the edit button sux
Anyway, IF your child will be removed from stage this
stageReference = this.parent;
will not work so its better to use something like
I also dont like this way so much, maybe the best would be to use the correct onAddedToStage event, but i would rather wait for the new flash to use itCode://(inside the class)
//(inside the constructor function)
hasStageReference = true;
//outside constructor function, this is the function that receives the //reference to the stage
function setStageReference(obj){
stageReference = obj;
//do stage stuff
stageReference.addEventListener("enterFrame", oef);
}
//on the stage
stage.addEventListener("added", addedHandler);
function addedHandler(ev){
if(ev.target.hasStageReference){
ev.target.setStageReference(this);
}
}
In earlier Flash versions "_name" property was direct access to objects, if you changed the _name object was only accessible with new name:
Not so in Flash 9. Like all properties, it has lost underscore and is now just "name".PHP Code:mc1._name="mc2";
//traces undefined
trace(mc1);
//traces mc2
trace(mc2);
First of, if you have objects placed directly on stage with F9, their name is locked and attempt to change it provides an error. Lets say movie clip is on stage with instance name mc1:
You can still change name of objects created by code, but changing name property will not change the object itself:PHP Code://gives error
mc1.name="mc2";
So the "name" is just like some variable inside the object, changing it wont change the object itself.PHP Code:import flash.display.Sprite;
var mc1:Sprite = new Sprite();
mc1.name = "mc2";
trace(mc1);
//gives error for using undefined variable mc2
trace(mc2);
All new display objects get default value assigned to name property when they are created, the default value is "instance+n" where n is number of childs on the current timeline:
Whats the use of it then? You can use getChildByName() method which returns child with given name:PHP Code:import flash.display.Sprite;
var mc1:Sprite = new Sprite();
//traces instance1
trace(mc1.name);
mc1.name = "mc2";
//traces mc2
trace(mc1.name);
PHP Code:import flash.display.Sprite;
var mc1:Sprite = new Sprite();
mc1.name = "mc2";
addChild(mc1);
//traces null
trace(getChildByName("mc1"));
//traces [object Sprite]
trace(getChildByName("mc2"));
loadMovie, loadVariables, MovieClipLoader, LoadVars are all gone from Flash 9. Loader class loads swf files and images, URLLoader loads XML and variables, sounds are still loaded using sound class.
Lets look at Loader class.
First you need to create new Loader object and new URLRequest object. Strings can not directly used, they must be converted into URLRequest. Once you have loader object, you can use load method to get extrenal file. Images and swf movies are loaded exactly same way.PHP Code:var ldr:Loader = new Loader();
var urlReq:URLRequest = new URLRequest("loadedmc.swf");
ldr.load(urlReq);
addChild(ldr);
Since loader is one of display objects, it can be added to stage directly without converting it into movie clip or image. However, you can not add childs to loader object.
Of course above example is not very good if the extrenal file is large and takes time to load. Luckily, loader class provides methods to know when content was successfully loaded:
Notice that you can not add listeners directly to loader object, you have to add them into contentLoaderInfo object. That object also provides access to bytesLoaded, bytesTotal and other data in case you wish to show information about loading process.PHP Code:ldr.contentLoaderInfo.addEventListener (Event.COMPLETE, done);
function done (ev:Event):void {
trace("completed loading");
}
Sometimes loading files may fail, maybe file was not found or connection was lost or for some other reason. It is good to check for error:
The loader object itself can be used to display stuff, but the actual image or movie it loaded is inside content object. For example if you loaded image and you want to access its bitmapData object, trying to get it from loader object gives an error:PHP Code:ldr.contentLoaderInfo.addEventListener (IOErrorEvent.IO_ERROR, badthings);
function badthings (ev:IOErrorEvent):void {
trace("loading went wrong");
}
instead, you use its content:PHP Code:trace(ldr.bitmapData);
PHP Code:trace(ldr.content.bitmapData);
there is also the event progress, wich broadcast an event with the propertys bytesLoaded and bytesTotal, wich can be good to make a preloader
Code:var re:URLRequest = new URLRequest("loaded_.swf");
var ld:Loader = new Loader();
ld.contentLoaderInfo.addEventListener("complete", ch);
ld.contentLoaderInfo.addEventListener("progress", pgHandler);
ld.load(re);
addChild(ld);
ld.y = 200;
function pgHandler(ev){
trace(" bytesLoaded: " + ev.bytesLoaded + " bytesTotal: " + ev.bytesTotal);
}
function ch(ev){
trace("complete!!");
}