dcsimg
A Flash Developer Resource Site

Page 1 of 3 123 LastLast
Results 1 to 20 of 52

Thread: [F9]Tips from starting with AS3

  1. #1
    Senior Member tonypa's Avatar
    Join Date
    Jul 2001
    Location
    Estonia
    Posts
    8,227

    [F9]Tips from starting with AS3

    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.

  2. #2
    Senior Member tonypa's Avatar
    Join Date
    Jul 2001
    Location
    Estonia
    Posts
    8,227

    Key listener needs focus

    Trying to make sample sprite and adding key listener to it so it will detect keys being up and down:
    PHP Code:
    //make new sprite
    var spr:Sprite = new Sprite();
    //add listeners
    spr.addEventListener(KeyboardEvent.KEY_DOWNkeyDownHandler);
    spr.addEventListener(KeyboardEvent.KEY_UPkeyUpHandler);
    //functions to trace keys
    function keyDownHandler(event:KeyboardEvent):void {
        
    trace("keyDownHandler: " event.keyCode);
    }
    function 
    keyUpHandler(event:KeyboardEvent):void {
        
    trace("keyUpHandler: " event.keyCode);

    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:
    stage.addEventListener(KeyboardEvent.KEY_DOWNkeyDownHandler);
    stage.addEventListener(KeyboardEvent.KEY_UPkeyUpHandler); 
    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.focus spr;
    spr.addEventListener(KeyboardEvent.KEY_DOWNkeyDownHandler);
    spr.addEventListener(KeyboardEvent.KEY_UPkeyUpHandler); 
    This will detect keys as long sprite does not lose focus (user could click on text field for example).
    Last edited by tonypa; 04-04-2007 at 05:23 AM.

  3. #3
    Senior Member tonypa's Avatar
    Join Date
    Jul 2001
    Location
    Estonia
    Posts
    8,227

    Attaching movie clips from library

    In earlier versions you could have movie clips attached by giving them linkage name and then using code like:
    PHP Code:
    this.attachMovie("linkagename""newmcname"1); 
    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.

    To add this movie clip on stage you first have to create new instance of that class:
    PHP Code:
    var newMC=new myMC(); 
    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:
    //position
    newMC.x=200;
    newMC.y=300;
    //add to stage
    this.addChild(newMC); 
    Last edited by tonypa; 04-04-2007 at 05:24 AM.

  4. #4
    Senior Member tonypa's Avatar
    Join Date
    Jul 2001
    Location
    Estonia
    Posts
    8,227

    Depths

    You could use any number for depth when attaching movie clips in earlier Flash:
    PHP Code:
    this.attachMovie("linkagename""mc"100); 
    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""mc1"100);
    //replace mc1 with mc2
    this.attachMovie("linkagename""mc2"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:
    container.addChildAt(mc0); 
    However, this will result in error:
    PHP Code:
    container.addChildAt(mc10); 
    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.

    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
    PHP Code:
    container.addChildAt(mc31); 
    you end up with 4 children: mc0 (depth0), mc3 (depth1), mc1 (depth2) and mc2 (depth3).

    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
    PHP Code:
    container.removeChildAt(1); 
    will result container having 3 chidren: mc0, mc1 and mc2 in depths 0, 1 and 2.
    Last edited by tonypa; 04-04-2007 at 05:25 AM.

  5. #5
    Untitled-1.fla strille's Avatar
    Join Date
    Mar 2001
    Location
    Sweden
    Posts
    1,626
    In AS 1/2.0 you attached a movie clip by specifying the linkage id, like this:
    Code:
    var n = 1;
    this.attachMovie("myMC"+n, "mc", 100);
    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:
    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();
    In this case "myMC1" is a movie clip in the library. So, the code above is equal to:
    Code:
    var newMC:MovieClip = new myMC1();

  6. #6
    Hype over content... Squize's Avatar
    Join Date
    Apr 2001
    Location
    Lost forever in a happy crowd...
    Posts
    5,928
    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.

  7. #7
    hippie hater Cimmerian's Avatar
    Join Date
    Oct 2006
    Location
    over there
    Posts
    599
    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
    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]);
    }
    length is a method, not a property like it is in arrays, so use it like this: length();
    Last edited by Cimmerian; 04-03-2007 at 07:35 PM.

  8. #8
    Filthy Gorgeous DancingOctopus's Avatar
    Join Date
    Sep 2003
    Location
    Sunny Australia.
    Posts
    478
    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?

  9. #9
    Senior Member tonypa's Avatar
    Join Date
    Jul 2001
    Location
    Estonia
    Posts
    8,227
    Quote Originally Posted by DancingOctopus
    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:

    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

  10. #10
    Filthy Gorgeous DancingOctopus's Avatar
    Join Date
    Sep 2003
    Location
    Sunny Australia.
    Posts
    478
    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

  11. #11
    Senior Member tonypa's Avatar
    Join Date
    Jul 2001
    Location
    Estonia
    Posts
    8,227

    Default values

    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
    PHP 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");

    The conversion from undefined to null is automatic
    PHP Code:
    var var1;
    if(
    var1==null){
        
    trace("var1 is not really null, but it is converted to null when compared");

    However, variable with type can not be converted into undefined value, this will result in warning:
    PHP Code:
    if(var2==undefined){
        
    trace("var2 is undefined");

    For booleans null is also not allowed, this will result in warning again:
    PHP Code:
    var var3:Boolean;
    if(
    var3==null){
        
    trace("var3 is null");

    For string, default value is null. Notice that it is not same as empty string (""):
    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");

    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.

    Integers are 0 by default:
    PHP Code:
    var var1:int;
    if(
    var1==0){
        
    trace("var1 is "+var1);

    but numbers have value of NaN which is not same as 0. This does not trace anything:
    PHP Code:
    var var2:Number;
    if(
    var2==0){
        
    trace("var2 is "+var2);

    Use isNaN function to check if number has no value:
    PHP Code:
    if(isNaN(var2)==true){
        
    trace("var2 is "+var2);

    "Not a number" results also from dividing 0 by 0 and taking square root from negative number:
    PHP Code:
    var var1=0;
    var 
    var2=0;
    trace(var1/var2);
    var 
    var3=-1;
    trace(Math.sqrt(var3)); 
    Notice that result from dividing number by 0 is Infinity or -Infinity:
    PHP Code:
    var var1=1;
    var 
    var2=-1;
    var 
    var3=0;
    trace(var1/var3);
    trace(var2/var3); 
    Last edited by tonypa; 04-04-2007 at 05:30 AM.

  12. #12
    Senior Member tonypa's Avatar
    Join Date
    Jul 2001
    Location
    Estonia
    Posts
    8,227

    More about variables

    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:
    PHP Code:
    var myVar1=9;
    trace(myVar1);
    myVar1="ab";
    trace(myVar1); 
    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 myVar2:Number=9;
    myVar2="ab";
    trace(myVar2); 
    If you try to change type later you get error message:
    PHP Code:
    var myVar3=9;
    myVar3:String="ab";
    trace(myVar3); 
    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 myVar4=9;
    var 
    myVar4=10
    In main timeline you can use this keyword or not, both ways you access to same variable. This traces 3:
    PHP Code:
    var myVar4=1;
    this.myVar4++;
    myVar4++; 
    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 myVar5=1;
    function 
    doStuff() {
        
    this.myVar5++;
    }
    doStuff();
    trace(myVar5); 
    But trying this is different:
    PHP Code:
    var myVar5=1;
    function 
    doStuff() {
        var 
    myVar5=10;
        
    myVar5+=10;
        
    this.myVar5++;
        
    trace(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 line
    PHP Code:
    myVar5+=10
    uses variable in the function, but using "this" keyword ignores new variable in the function and uses one declared outside.

  13. #13
    Hey Timmy!!! walsher's Avatar
    Join Date
    Jan 2005
    Location
    Latrobe, PA
    Posts
    1,899
    Wow, thanks for the great tips tony, strille and Cimmerian. They should prove most usefully when I finally go over to CS3.

  14. #14
    Senior Member walnoot's Avatar
    Join Date
    Apr 2005
    Posts
    754
    Bookmarked! Just like to say thank you.

  15. #15
    M.D. mr_malee's Avatar
    Join Date
    Dec 2002
    Location
    Shelter
    Posts
    4,140

    resource

    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.
    lather yourself up with soap - soap arcade

  16. #16
    Zombie Coder EvilKris's Avatar
    Join Date
    Jun 2006
    Location
    Fukuoka, Japan.
    Posts
    796
    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?

  17. #17
    Senior Member tonypa's Avatar
    Join Date
    Jul 2001
    Location
    Estonia
    Posts
    8,227
    Quote Originally Posted by EvilKris
    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 mr_malee
    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
    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).
    Last edited by tonypa; 04-05-2007 at 03:10 AM.

  18. #18
    Senior Member tonypa's Avatar
    Join Date
    Jul 2001
    Location
    Estonia
    Posts
    8,227

    Detecting when your game loses focus

    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:
    PHP Code:
    stage.addEventListener(Event.ENTER_FRAMEmoveAll); 
    You can now use Deactivate event to remove listener to main function and Activate event to re-add it:
    PHP Code:
    stage.addEventListener(Event.ACTIVATEgoagain);
    stage.addEventListener(Event.DEACTIVATEstopit);
    function 
    goagainevent:Event ) : void{
       
    stage.addEventListener(Event.ENTER_FRAMEmoveAll);
    }
    function 
    stopitevent:Event ) : void{
       
    stage.removeEventListener(Event.ENTER_FRAMEmoveAll);

    Flash9 also has event to detect when mouse cursor leaves your game stage:
    PHP Code:
    stage.addEventListener(Event.MOUSE_LEAVEstopit); 
    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.

    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.

  19. #19
    hippie hater Cimmerian's Avatar
    Join Date
    Oct 2006
    Location
    over there
    Posts
    599
    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!

  20. #20
    Hype over content... Squize's Avatar
    Join Date
    Apr 2001
    Location
    Lost forever in a happy crowd...
    Posts
    5,928
    "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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  




Click Here to Expand Forum to Full Width

HTML5 Development Center