kirupaForum

kirupaForum (http://www.kirupa.com/forum/index.php)
-   Flash ActionScript (http://www.kirupa.com/forum/forumdisplay.php?f=9)
-   -   ActionScript 3 Tip of the Day (http://www.kirupa.com/forum/showthread.php?t=223798)

senocular 12-24-2006 06:13 AM

Those are in the old XML Class (now called XMLDocument). In AS3 you should be using the new E4X XML class (XML). See:
XML vs. XMLDocument
There are links to the APIs for each there.

tpspoons 12-24-2006 06:17 AM

Sorry thats what I meant, in e4x is there an alternative for previousSibling and nextSibling? I looked in the flex help files but couldn't find one... Already checked the language reference I was just hoping maybe you know of a simple alternative?

senocular 12-24-2006 06:19 AM

no, but its not hard to do manually using parent() children() and childIndex() +/- 1 ;)

tpspoons 12-24-2006 06:21 AM

Thanks :D Il check it out.

Edit: Shouldn't this thread be stickied?

tpspoons 12-26-2006 05:43 PM

(Didn't wan't to make a new thread...)

In flex, how do you repeatadely load XML at runtime? Using the HTTPService component loading it is fine, but if the XML is edited whilst the swf is running, the component doesn't load the new XML, instead it loads the XML that was originally loaded. Does that make sense?

kishydvn 12-27-2006 01:57 AM

I forgot about kirupa forms and searching else where about actionscript3 knowledge. I am so happy to see thse tips and thanks a lot for providing this support to flash lovers.

Dan@NASA 12-27-2006 09:08 AM

STICKY!

Dazzer 12-27-2006 09:16 AM

just wondering...

Why would you need parent child siblings functions in AS3?

TheCanadian 12-27-2006 10:24 AM

Quote:

Originally Posted by Dazzer (Post 2029833)
just wondering...

Why would you need parent child siblings functions in AS3?

What do you mean?

Dazzer 12-27-2006 10:39 AM

sorry forgot to quote.
Quote:

Originally Posted by tpspoons (Post 2028387)
Sorry thats what I meant, in e4x is there an alternative for previousSibling and nextSibling? I looked in the flex help files but couldn't find one... Already checked the language reference I was just hoping maybe you know of a simple alternative?


tpspoons 12-27-2006 10:42 AM

Just experimenting with loading XML in flex, and making a previous and next buttons. It would be easier using the previous and next sibling functions but doing it by hand isn't that difficult. Still, I thought AS3 was suppose to be simpler?

Dazzer 12-27-2006 10:46 AM

no i thought it was supposed to be more powerful, and more familiar to other languages...

and you can handle XML like arrays now (which is so much better for parsing data) cuz now they use XMLList, instead of childNode. I never really liked

ActionScript Code:
child = child.nextSibling();
if (child != null)
{
trace(blah);
}

tpspoons 12-27-2006 10:54 AM

From Actionscript 3.0 Overview:

Quote:

Simplicity: The language is intuitive enough for developers to be able to read and write programs without constantly consulting a reference manual.
Exept thats the problem, they made many things more complicated and harder to memorize. Like for example they removed onReleaseOutside, so you have to come up with a longer alternative. And even the new way of doing onRelease and onPress using listeners is longer and unnecessary.

tpspoons 12-27-2006 02:35 PM

How do you create a tiled background in as3? I tried converting a code I used for a old project, but then I came into a few problems and now I'm just confused... The biggest problem probably being that I couldn't use beginBitmapFill. Any ideas? Thanks. (sorry to be asking so many questions)

TheCanadian 12-27-2006 03:20 PM

Pretty well the same as AS2:
ActionScript Code:
import flash.display.BitmapData;
import flash.geom.Rectangle;

var square:Rectangle = new Rectangle(0, 0, 10, 10);
var tile:BitmapData = new BitmapData(20, 20, false, 0xFFFFFF);
tile.fillRect(square, 0xFF0000);
square.x = 10;
square.y = 10;
tile.fillRect(square, 0xFF0000);

this.graphics.beginBitmapFill(tile);
this.graphics.lineTo(this.stage.stageWidth, 0);
this.graphics.lineTo(this.stage.stageWidth, this.stage.stageHeight);
this.graphics.lineTo(0, this.stage.stageHeight);
this.graphics.lineTo(0, 0);
this.graphics.endFill();

tpspoons 12-27-2006 03:33 PM

Thanks :P But how would you do that with a bitmap from the library/ dynamic bitmap? Flash 9 doesm't let you set linkage Id's, so how would you connect to them?

TheCanadian 12-27-2006 04:11 PM

In AS3, you must give objects in the library class association in order to instantiate them with AS. If you don't have a class for your bitmap (ie you don't need to extends BitmapData with more methods) then you can type in a class name and Flash will automatically create one for you which will extend BitmapData. Than you just call that classes constructor, assign the instance to a variable and tile it:


ActionScript Code:
import flash.display.BitmapData;
var tile:BitmapData = new MyImage();
this.graphics.beginBitmapFill(tile);
this.graphics.lineTo(this.stage.stageWidth, 0);
this.graphics.lineTo(this.stage.stageWidth, this.stage.stageHeight);
this.graphics.lineTo(0, this.stage.stageHeight);
this.graphics.lineTo(0, 0);
this.graphics.endFill();

You really should ask these questions in a seperate thread :)

tpspoons 12-27-2006 05:06 PM

Thanks! Since they were pritty simple questions, didn't wan't to make a new thread. But Il remember that next time.

TheCanadian 12-27-2006 05:08 PM

Glad to help :hoser:

tpspoons 12-29-2006 07:30 AM

Quote:

Originally Posted by senocular (Post 1878656)
Like ActionScript 1 and 2, ActionScript 3 also has a drawing API that allows you to draw vector lines and shapes dynamically in movie clips and sprites. With ActionScript 3, however, the drawing API is now used off of an object within display objects (movie clips, sprites, etc.) defined as graphics (flash.display.Graphics). This graphics property represents the dynamic drawing layer where drawing API drawings exist. Like before, it is placed below all children of the target object. Also, in ActionScript 3, you have new methods that help you more easily create rectangles, circles, and even rounded rectangles. These include:
  • drawCircle(x:Number, y:Number, radius:Number):void
  • drawEllipse(x:Number, y:Number, width:Number, height:Number):void
  • drawRect(x:Number, y:Number, width:Number, height:Number):void
  • drawRoundRect(x:Number, y:Number, width:Number, height:Number, ellipseWidth:Number, ellipseHeight:Number):void

Example:
ActionScript Code:
// draw a blue rounded rectangle:
var square:Sprite = new Sprite();
square.graphics.beginFill(0xFF);
square.graphics.drawRoundRect(0, 0, 100, 50, 10, 10);
square.graphics.endFill();
addChild(square);

When using the drawCircle, drawRect, drawRoundRect ETC, you don't need the endFill()? Do you?

Dazzer 12-29-2006 08:08 AM

nope.

Those functions have a built in endFill().

tpspoons 12-29-2006 08:12 AM

Didn't think so.

(Maybe Senocular should edit his post :P)

TheCanadian 12-29-2006 03:06 PM

No, they don't call endFill, so it is necessary to end the filling operation. Otherwise it will keep filling and you will get something like this if you keep drawing:
ActionScript Code:
// draw a blue rounded rectangle:
var square:Sprite = new Sprite();
square.graphics.beginFill(0xFF);
square.graphics.drawRoundRect(0, 0, 100, 50, 10, 10);
square.graphics.lineTo(550, 400);
square.graphics.lineTo(550, 0);
addChild(square);

tpspoons 12-29-2006 04:09 PM

^
Actually this is directly from the flash.display.graphics (from the Flex 2 Language Reference).

Quote:

Flash Player does not render the fill until the endFill() method is called. (The drawCircle(), drawEllipse(), drawRect(), and drawRoundRect() methods automatically invoke the endFill() method.)

TheCanadian 12-29-2006 04:36 PM

Well the example above is evidence to the contrary, it's certainly not the first time the Adobe LR has been wrong.

Krilnon 12-29-2006 06:15 PM

It would be kind of silly if any of those methods called endFill anyway. If you're allowed to draw with the other drawing methods after calling beginFill and before calling a convenience method, it wouldn't make sense to essentially restrict you from drawing after that without calling beginFill again.

Dazzer 12-29-2006 08:21 PM

lots of booboos. jeez...

skindc 01-12-2007 03:53 PM

In reference to bitmap from library tip();;

I understand your methods here, but can this be aplied to a movieclip with a time line in the library. I have an animation of a bird flying that had to be built in Flash authoring environment and I want this to be used on call within one of my classes. can I call this in the same way. Oh and it has already been set to a class so how do I reference that class do I target it through the full package path or just simply the class name?
Cheers, Skin

Flashthinker 01-19-2007 05:37 AM

Senocular, in your post about creating custom events you used this:

public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void {
eventDispatcher.addEventListener.apply(null, arguments);
}

I was wondering what is the apply() for? What does it do?

Thanks,

senocular 01-19-2007 07:44 AM

apply
http://livedocs.macromedia.com/flex/...on.html#apply()

It lets you call a function with an array as its arguments instead of making you write them as a comma delimited list. This makes it much easier to work with functions that can take any number of arguments and you have values to be sent to that function as an array

in the addEventListener example, I just used it to make it easier to transfer all of the arguments from the class's addEventListener to the addEventListener method in the eventDispatcher object.

lowdown 01-28-2007 01:04 AM

Quote:

Originally Posted by senocular (Post 1876824)
The release of Flex Builder 2 is around the corner and though the next version of Flash is still a ways away, ActionScript 3 will be a big part of Flex 2 and the impending release of Flash Player 9 (which arrives with Flex). ActionScript 3 is the next step forward and to help with the transition (for those of you deciding to make it), I thought, since I've been working with AS3 a bit lately, I'd make a new Tip of the Day thread for ActionScript 3.0 to help people prepare. So here we go:

I wanted to say thanks for doing this senocular. This thread has been a huge help in the AS3 learning process.

tahooie 01-30-2007 02:47 PM

How I got around this
 
Quote:

Originally Posted by v_gyku (Post 1951006)
Will the following code run? or is it somthing more I need to code?
I copy pasted the following code in the actions panel and tested the movie.
It gave a compile error: 1037: Packages cannot be nested.
Output window: ReferenceError: Error #1065: Variable MainTimeline is not defined.

Am i doing somthing wrong?

I kept getting the "Packages cannot be nested" or "Classes must not be nested" errors. I was referencing my class file incorrectly in my mxml file.

This is the WRONG way:
<mx:Script source="MyClass.as"/>

By changing it to this way the problem was fixed:
<mx:Script>
<![CDATA[
import MyClass;
// then instantiate the class as usual, but make sure there is nothing
// in it's constructor that will do anything visual, as the app has not yet
// finished being created.
private var mc:MyClass = new MyClass;
]]>
</mx:Script>

glidealong 02-11-2007 10:44 PM

Quote:

Originally Posted by senocular (Post 1939827)
The only thing duplicateMovieClip does that this does not is copy dynamic drawing information. Currently, the graphics object in display objects cannot be duplicated so there is no way to obtain that information for duplicates in duplicateDisplayObject.

That has taken away all the fun associated with it. I was drawing a curve with a cubic equation(2x^3 -3x^2 + 1) and I wanted to duplicate the curve plotted on the positive X-Axis along the negative X-Axis, ie. I need to take a mirror image of the curve along the Y-Axis.. I hope u understand. But since I am redrawing the curve with every mouse move(to make the current stage.mouseX as origin) i have to duplicate the sprite on every mouse move.. Is it a distant dream???

byronb 02-22-2007 05:25 AM

Quote:

Originally Posted by senocular (Post 1877502)
ActionScript 3 is the next release of ActionScript that will be supported in Flash Player 9. Flex 2 applications are built using ActionScript 3 and the next version of Flash (code named BLAZE) will support it when it's released some time after Flex. Unlike ActionScript 2, ActionScript 3 uses an entirely new virtual machine providing it with new robust features and increased performance.

More details on available and upcoming products can be found on http://www.adobe.com/ and http://labs.adobe.com/ (where both the Flex 2 beta and Flash Player 9 beta are currently available for download)

Thank you very much for these great tips, i especially enjoyed
  1. Cleaning Up Event Listeners
  2. Detecting Addition to or Removal from Stage

senocular 04-03-2007 10:22 AM

Overriding clone in Events
 
When creating custom events, you should always override the clone() method. Though this is not necessary in all situations, it is best practice and will save you from errors in the situations where it is.

Why do you need to override clone? Well, the clone method creates a copy of your event (or object - whatever object has the clone event; this isn't limited to Event objects). The default clone method inherited by the Event class or whatever class your custom class extends, will return an event object of the type of that class, not your custom event subclass. In the situations where a clone is needed, it is needed to be of the same type of your class, not the class it extends.

When is clone needed? Clone is needed whenever you re-dispatch an already targeted event. Whenever you create a new event instance, that event instance has a null target. When it is eventually dispatched, that target is assigned to be whatever object did the dispatching. Should that, now targeted, event ever be re-dispatched or dispatched a second time, a clone of that event is created and the new target assigned to the clone. It is at this point when the overridden clone method is needed, otherwise an error will occur when you have a type mismatch.

Note: when extending clone(), be sure to use the same method signature as defined by the Event class. This means the return value of clone must be Event, not your custom class. Because your custom class inherits from event, the type is still correct, but the actual instance returned will be, not an Event instance specifically, but an instance of your custom event.

ActionScript Code:
package {

    import flash.events.Event;
   
    public class CustomEvent extends Event {

        public function CustomEvent(type:String, bubbles:Boolean, cancelable:Boolean) {
            super(type, bubbles, cancelable);
        }

        // override clone so the event can be redispatched
        public override function clone():Event {
            return new CustomEvent(type, bubbles, cancelable);
        }
    }
}

senocular 04-03-2007 10:22 AM

Class member enumeration
 
Enumeration (the ability to cycle through an object's members in a loop) in ActionScript 3 now only works with dynamic definitions in dynamic classes. Non-dynamic classes do not provide enumerable properties or methods. The following class, for example, has no enumerable members that would be recognized in a for..in loop.
ActionScript Code:
package {
   
    public class EnumerateClass {
   
        public var variable:String = "value";
        public function method():void {}
    }
}


ActionScript Code:
var example:EnumerateClass = new EnumerateClass();
for (var key:String in example) {
    trace(key + ": " + example[key]); // no output
}


Even when dynamic, the above class will not have enumerable members because the variable and method definitions are themselves not dynamic.
There is a setPropertyIsEnumerable method located in the Object class, but it too only works with dynamic properties. Consider the following amended class definition.

ActionScript Code:
package {
   
    public dynamic class EnumerateClass {
   
        public var variable:String = "value";
        public function method():void {}
           
        public function EnumerateClass(){
            this.dynamicVar = 1;
            this.dynamicVar2 = 2;
            this.setPropertyIsEnumerable("dynamicVar2", false);
        }
    }
}


This class is now dynamic and has 2 dynamic properties, dynamicVar and dynamicVar2. As dynamic properties these would show up in for..in loop enumeration. The use of setPropertyIsEnumerable, however, prevents dynamicVar2 from showing up.

ActionScript Code:
var example:EnumerateClass = new EnumerateClass();
for (var key:String in example) {
    trace(key + ": " + example[key]); // dynamicVar: 1
}


Using Object.propertyIsEnumerable() you can test to see whether or not a property is enumerable for a class instance.

ActionScript Code:
trace(example.propertyIsEnumerable("variable")); // false
trace(example.propertyIsEnumerable("dynamicVar")); // true
trace(example.propertyIsEnumerable("dynamicVar2")); // false
 

senocular 04-03-2007 10:23 AM

Flash 9: Timeline navigation and code execution
 
In ActionScript 1 and 2, when you navigated between multiple frames during the same frame of execution, the code on each one of those frames would be executed before the frame completed in Flash. For example, consider a movie clip named "tracer" of three frames stopped on frame 1 and resting on the main timeline. In frame 2 of that movie clip is a trace statement tracing "frame 2". Similarly, in frame 3 there is a trace statement tracing "frame 3". The following code on the main timeline would cause both trace statements to run.
ActionScript Code:
tracer.gotoAndStop(2);
tracer.gotoAndStop(3);


In ActionScript 3, the Flash player waits until the screen is about to be rendered and at that point in time runs the frame script of the current frame and only the current frame, despite what other frames may have been traversed within the actions occuring during that frame.

Note: You may find that scripts unexpectedly run more than once per frame if navigating across multiple frames during one frame cycle. If possible, you should not try to navigate more than one frame at a time.

senocular 04-03-2007 10:23 AM

Flash 9: addFrameScript
 
When you publish an ActionScript 3 movie from the Flash Authoring environment, Flash will automatically convert timelines with scripts written in them into classes with a definitions based on the timeline scripts used. Variables and functions get converted into class members and frame scripts specific to frames become methods to be called on those frames. But how does Flash make that association? This is made by an undocumented addFrameScript() method. This method takes a collection of frame (zero-based) - method pairs that associates a method with a frame on the timeline. When that frame on the timeline is reached, the method is called.
ActionScript Code:
MovieClip.addFrameScript(frame:int, method:Function, [frame:int, method:Function...]):void;

The following example has two methods, onFrame3 and onFrame6 which gets called on frames 3 and 6 respectively (note that they are added by addFrameScript as frames 2 and 5 since the frame value there is 0-based).
ActionScript Code:
package {
   
    import flash.display.MovieClip;
   
    public class DocumentClass extends MovieClip {
       
        public function DocumentClass(){
            addFrameScript(2, onFrame3, 5, onFrame3);
        }
       
        public function onFrame3():void {
            trace("frame 3: "+currentFrame);
        }
        public function onFrame6():void {
            trace("frame 6: "+currentFrame);
        }
    }
}

Only one method can be associated with any one frame. If you ever need to remove a frame, use null as the frame method
ActionScript Code:
addFrameScript(2, null); // removes frame 3 script
 

senocular 04-03-2007 10:24 AM

Key.isDown in AS3
 
In ActionScript 2, you could use Key.isDown(keyCode) to determine whether or not a key was being pressed on the keyboard. This command is no longer available in ActionScript 3. In fact, there is no Key object in ActionScript 3. You can still access keyCodes by name, but through the Keyboard (flash.ui.Keyboard) class. For key recognition in ActionScript 3, you have to use keyboard events or, more specifically the KeyboardEvent.KEY_DOWN and KeyboardEvent.KEY_UP events. When a key is pressed on the keyboard, the KeyboardEvent.KEY_DOWN is dispatched and you can tell which key was pressed by checking KeyboardEvent.keyCode in the event handler. Same applies to keys being released in the KeyboardEvent.KEY_UP.

Using these events, you could recreate the functionality provided by the Key class in ActionScript 2. However, you should know that the KeyboardEvents only work when the Flash player has focus. This means a key could be pressed in Flash and released outside of Flash without Flash knowing that it was released (not having received the KEY_UP event). As a result, you should assume all keys released upon deactivation (loss of focus) of the Flash player. The following recreation of the Key class takes that into consideration.
ActionScript Code:
package {
   
    import flash.display.Stage;
    import flash.events.Event;
    import flash.events.KeyboardEvent;
   
    /**
     * The Key class recreates functionality of
     * Key.isDown of ActionScript 1 and 2. Before using
     * Key.isDown, you first need to initialize the
     * Key class with a reference to the stage using
     * its Key.initialize() method. For key
     * codes use the flash.ui.Keyboard class.
     *
     * Usage:
     * Key.initialize(stage);
     * if (Key.isDown(Keyboard.LEFT)) {
     *    // Left key is being pressed
     * }
     */

    public class Key {
       
        private static var initialized:Boolean = false;  // marks whether or not the class has been initialized
        private static var keysDown:Object = new Object()// stores key codes of all keys pressed
       
        /**
         * Initializes the key class creating assigning event
         * handlers to capture necessary key events from the stage
         */

        public static function initialize(stage:Stage) {
            if (!initialized) {
                // assign listeners for key presses and deactivation of the player
                stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
                stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
                stage.addEventListener(Event.DEACTIVATE, clearKeys);
               
                // mark initialization as true so redundant
                // calls do not reassign the event handlers
                initialized = true;
            }
        }
       
        /**
         * Returns true or false if the key represented by the
         * keyCode passed is being pressed
         */

        public static function isDown(keyCode:uint):Boolean {
            if (!initialized) {
                // throw an error if isDown is used
                // prior to Key class initialization
                throw new Error("Key class has yet been initialized.");
            }
            return Boolean(keyCode in keysDown);
        }
       
        /**
         * Event handler for capturing keys being pressed
         */

        private static function keyPressed(event:KeyboardEvent):void {
            // create a property in keysDown with the name of the keyCode
            keysDown[event.keyCode] = true;
        }
       
        /**
         * Event handler for capturing keys being released
         */

        private static function keyReleased(event:KeyboardEvent):void {
            if (event.keyCode in keysDown) {
                // delete the property in keysDown if it exists
                delete keysDown[event.keyCode];
            }
        }
       
        /**
         * Event handler for Flash Player deactivation
         */

        private static function clearKeys(event:Event):void {
            // clear all keys in keysDown since the player cannot
            // detect keys being pressed or released when not focused
            keysDown = new Object();
        }
    }
}

senocular 04-03-2007 10:24 AM

Scale and Alpha Ranges
 
One thing to be weary of, especially when trying to port older code to ActionScript 3 is that the ranges for many popular properties have changed. A few properties that, before, may have had ranges of 0 to 100 are now 0 to 1. Here is a couple of properties that changed; be on a look out for others:
Code:

ActionScript 2.0  | ActionScript 3.0
_xscale: 0 - 100  | scaleX: 0 - 1
_yscale: 0 - 100  | scaleY: 0 - 1
_alpha:  0 - 100  | alpha:  0 - 1



All times are GMT -7. The time now is 10:35 AM.

Powered by vBulletin® Version 3.6.4
Copyright ©2000 - 2007, Jelsoft Enterprises Ltd.
Copyright 2004 - kirupa.com