Page 22 of 45 FirstFirst ... 12202122232432 ... LastLast
Results 316 to 330 of 669

Thread: ActionScript 3 Tip of the Day

  1. #316

    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.
    Code:
    package {
    	
    	public class EnumerateClass {
    	
    		public var variable:String = "value";
    		public function method():void {}
    	}
    }
    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.

    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.

    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.

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

  2. #317

    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 "child_mc" 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.
    Code:
    child_mc.gotoAndStop(2);
    child_mc.gotoAndStop(3); // only code executed
    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.

  3. #318

    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.
    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).
    Code:
    package {
    	
    	import flash.display.MovieClip;
    	
    	public class DocumentClass extends MovieClip {
    		
    		public function DocumentClass(){
    			addFrameScript(2, onFrame3, 5, onFrame6);
    		}
    		
    		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
    Code:
    addFrameScript(2, null); // removes frame 3 script

  4. #319

    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.
    Code:
    // Key.as
    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();
    		}
    	}
    }

  5. #320

    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

  6. #321

    Errors: Referencing properties from a null reference

    If you reference a property from an undefined variable or a variable with no value or a value of null in ActionScript 3 the Flash player will throw a runtime error.
    TypeError: Error #1009: Cannot access a property or method of a null object reference.
    In the Flash authoring environment, or in Flex debugging (or simply running the SWF in the debug player), you will see this as an error message. In the "release" Flash player and Flash player plugin, the error will fail silently, however any remaining script within the block will be skipped. In ActionScript 2, the error was silent and no error was thrown allowing the remaining script to be executed

    This is something to be careful of when writing AS3 code, especially when in the AS2 mindset when those errors go unpunished. You should always make sure that you are referencing the correct property of the correct object type and make sure that the object is not null before attempting to access or check a property from it. You can also encase code which might suffer from this in a try-catch block so the error will be caught and remaining script can be executed if an error does occur.

    Works in AS2, not AS3 if objectReference may be null
    Code:
    if (objectReference.property) {
    	// code
    }
    Note: if its possible that the value may be 0 or false (or an empty string or anything else that might result in a false value) you might want to compare to == null in the if statement.

    Works in AS3
    Code:
    if (objectReference && objectReference.property) {
    	// code
    }
    You can also use try-catch in AS3
    Code:
    try {
    	if (objectReference.property) {
    		// code
    	}
    }catch(err:Error){ }
    For try-catch, you could react to the error, but you don't have to. What it will allow is script following the block to continue executing which would not happen if the error was uncaught.

  7. #322
    Note: I also reorganized the first post to list the tips by topic. New tips will sit in the "Latest Additions" category until a new set are added. It will probably be a few days (weeks?) before that happens so they'll sit there for a while.

  8. #323

    Runtime Font Loading

    BurzaoneDynamicFont.as
    Code:
    /*       Author: burzaone         */
    package pl.burzaone.fonts
    {
        import flash.display.Loader;
        import flash.display.Sprite;
        import flash.events.Event;
        import flash.net.URLRequest;
        import flash.text.TextField;
        import flash.text.TextFieldAutoSize;
        import flash.text.TextFormat;
        import flash.text.AntiAliasType;
        import flash.text.Font;
        import flash.system.ApplicationDomain;
        
        [SWF( width="300" , height="200" , backgroundColor="0xffffff" , frameRate="31" )]
        
        public class BurzaoneDynamicFont extends Sprite {
            
            public function BurzaoneDynamicFont() {
                loadFont("MyFont.swf");
            }
            
            private function loadFont(url:String):void {
                var loader:Loader = new Loader();
                loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
                loader.load(new URLRequest(url));
            }
            
            private function completeHandler(event:Event):void {
                var MyFont:Class = event.target.applicationDomain.getDefinition("MyFont") as Class;
                Font.registerFont( MyFont );
                test();
            }
            
            public function test():void {
                var tf:TextField = new TextField();
                tf.defaultTextFormat = new TextFormat("ArialAbyMiecPewnosc", 16, 0);
                tf.embedFonts = true;
                tf.antiAliasType = AntiAliasType.ADVANCED;
                tf.autoSize = TextFieldAutoSize.LEFT;
                tf.border = true;
                tf.text = "burzaone burzaone\n\tburzaone burzaone\nburzaone burzaone\n\tburzaone burzaone\n0 1 2 3 4 5 6 7 8 9\n";
                tf.rotation = 15;
                tf.x = 50;
                tf.y = 50;
                addChild(tf);
            }
            
        }
        
    }
    MyFont.as
    Code:
    /*       Author: burzaone         */
    package pl.burzaone.fonts
    {    
        import flash.text.Font;
        
            /*  plik ARIALN.TTF musi się znajdować w tym samym katalogu co plik as  */
        [Embed(source='ARIALN.TTF' , fontName='ArialAbyMiecPewnosc' , mimeType='application/x-font' , unicodeRange='U+0030-U+0039 , U+0061-U+007A' , fontWeight='normal' , fontStyle='normal')]
        
        public class MyFont extends Font {}
    }
    * fontFamily == fontName

    * fontWeight and fontStyle default has normal
    * value for fontWeight => bold | heavy | normal
    * value for fontStyle => italic | oblique | normal

    * Embed fonts:
    ________* source="..." => path to file
    ________* systemFont="..." => system name fonts

  9. #324

    Available ActionScript packages

    For ActionScript 3, the Flash Player has a collection of built-in classes that are hard coded into the Flash Player itself. These are located in the 'flash' package and are always available to any AVM2 (AS3) SWF running in Flash Player 9 or greater.

    Flex 2 is built on the mx framework or the collecton of classes that belong in the 'mx' package. In ActionScript 2, both Flex (1) and Flash used the mx collection for things like components, transitions and animations, etc. For ActionScript 3, only Flex uses the mx framework and the classes defined within (which are separate though ofen similar to the respective AS2 version).

    Flash, on the otherhand, has a new collection of classes defined in the 'fl' package. These classes contain the Flash Authoring components and other classes used to work with AS3 in the Flash IDE. Note that the components used in Flash and those used in Flex are not the same.

    Additionally, the Flash authoring environment also has an 'adobe' package for classes used to interact with the Flash authoring environment in extensions and custom Flash panels.

    With Apollo, you have some additional classes available specific to the runtime. These classes are actually added to the flash packages and are only available when a SWF is being run in Apollo. They're still native to the player, but only the Apollo player provides them to your SWF.

    AS3 package Summary:
    • flash (always accessible, core player classes, additional classes added with Apollo)
    • mx (Flex only, required for Flex components)
    • fl (Flash only, Flash components and extras)
    • adobe (Flash only, extensions/extending Authoring tool)

    For information on each package and its contents, see the available documentation:
    Flex: http://livedocs.adobe.com/flex/201/langref/
    Flash: http://livedocs.adobe.com/flash/9.0/...riptLangRefV3/
    Apollo: http://livedocs.adobe.com/apollo/1.0/aslr/

    Note: Apollo-specific classes reside in the flash and mx packages.

  10. #325

    Animator class in AS3 (Flash CS3)

    The Animator class (fl.motion.Animator) is a new ActionScript class in Flash CS3 that describes and executes timeline animations in XML and ActionScript. This is not an upgrade of nor a replacement of the Tween class available in previous versions of Flash. That class is still available in Flash though now as fl.transitions.Tween. The Animator class is designed specifically to act as a direct representation of timeline animations and works with new the Copy Motion as ActionScript 3.0 feature in Flash CS3. The following is an example of a 20 frame motion tween (moving a movie clip from (50, 75) to (150, 75)) copied to ActionScript 3.0 using the Copy Motion as ActionScript 3.0 feature:
    Code:
    import fl.motion.Animator;
    var target_mc_xml:XML = <Motion duration="20" xmlns="fl.motion.*" xmlns:geom="flash.geom.*" xmlns:filters="flash.filters.*">
    	<source>
    		<Source frameRate="30" x="50" y="75" scaleX="1" scaleY="1" rotation="0" elementType="movie clip" symbolName="source_mc">
    			<dimensions>
    				<geom:Rectangle left="0" top="0" width="100" height="100"/>
    			</dimensions>
    			<transformationPoint>
    				<geom:Point x="0" y="0"/>
    			</transformationPoint>
    		</Source>
    	</source>
    
    	<Keyframe index="0" tweenSnap="true" tweenSync="true">
    		<tweens>
    			<SimpleEase ease="0"/>
    		</tweens>
    	</Keyframe>
    
    	<Keyframe index="19" x="100"/>
    </Motion>;
    
    var target_mc_animator:Animator = new Animator(target_mc_xml, target_mc);
    target_mc_animator.play();
    All the necessary information for the animation is stored in XML. Each XML node represents a class instance in Flash that the Animator instance (created near the bottom of the script) uses to animate a display object called target_mc.

    In terms of creating tweened animations manually in ActionScript, you will want to stick to using the Tween class. The Animator class is best when used with the Copy Motion as ActionScript 3.0 feature as creating Animator tweens from scratch can be a little difficult and offer no real advantage to the Tween class.

  11. #326

    Numeric Calculations: Number vs. int Speed

    The new int data type in ActionScript 3.0 is a new type for Number. Number data types represent floats (double), or numbers with fraction or decimal values. The int type are whole numbers with no fractions or decimals. Additionally, the int data type can take advantage of fast calculations used for bitwise operations (<<, >>, &, ^, and |) so a numeric value typed as an int in ActionScript 3.0 will be able to calculate bitwise operations faster than that same value if typed as a Number.
    Code:
    var valueN:Number = 10;
    result = valueN << 2; // not so fast
    
    var valueI:int = 10;
    reesult = valueI << 2; // Fast!
    Most of this speed, however, is limited to bitwise operations. Normal mathematical operations can actually be slower for ints. The reason for this is that ECMAScript (ActionScript) needs to calculate those operations as Number no matter what the data type of your original value. What this means is that if you multiply two ints together, Flash will need to internally cast or convert those values to Number and then perform the operation. For these basic mathematical operations, Number can actually be faster than int. Depending on how you work with your numbers, if you're looking for speed, you may need to type appropriately.

    You still get the best performance out of ints and bitwise operations though. If you're truely looking for the best performance (and ActionScript 3.0 is already fast) then you may be able to find places where you can substitute int-bitwise operations in place of other numeric operations. Bitwise shifting, for example, can also be represented as multiplication and division. Shifting left multiplies by factors of 2 and shifting right divides:
    Code:
    << 1  =  * 2
    << 2  =  * 4
    << 3  =  * 8
    << 4  =  * 16
    ...
    >> 1  =  / 2
    >> 2  =  / 4
    >> 3  =  / 8
    >> 4  =  / 16
    ...
    Most of the performance gained is minimal. And really, the performance lost from using multiplication ints is fairly minimal as well. The largest gap of performance between the Number and int types is the difference between bitwise operations. They tend to be much slower with Number types. If you're working with bitwise operations, you should really be using ints over Number.

  12. #327

    Flash CS3: Setting MovieClip Base Classes

    With ActionScript 3.0 in Flash CS3, you now have the option to specify not only classes for movie clip symbols in the library, but also base classes for those symbols. In the linkage dialog there is option for Class and below that an option for Base Class. Specifying a class lets you associate that symbol with a specific class. Creating an instance of that class then creates an instance of that symbol. When you specify a base class, you are associating that class with the symbol but as a subclass of the symbol. Another class will act as the symbol class - and this can be defined just as a name in the Class area where Flash will create the class definition automatically. This lets you have one class that you can use among multiple movie clip symbols while still having each of those symbols uniquely identified through an automatic class instance. Note: remember to use the full class name for the Class or Base class, including the package path.

  13. #328

    Adding an isPlaying Property to MovieClips

    Though you cannot modify the built-in classes of ActionScript, you can extend them, or use them as templates to make your own classes that have all of the original class's functionality plus more. By extending the MovieClip class in ActionScript with a custom class, you can add a custom isPlaying property to your MovieClips that will let you know when a movie clip is playing or not.

    When making a custom class that you will want to use for multiple symbols, you would specify the class as being a base class for those symbols. In the case of the custom class for making an isPlaying property, you might want to use it for all movie clip symbols in your library so that all symbols have this functionality. You can also just set the class as the base class for the movie clip symbols you wish to use it with.

    The class itself extends MovieClip and overrides all MovieClip-specific methods that relate to frame navigation. In each of those methods the isPlaying property is set as necessary and the original method is called to retain the functionality of that method. Here is the class:
    Code:
    package {
    	
    	import flash.display.MovieClip;
    	
    	/**
    	 * MovieClip class that adds an isPlaying property
    	 * to indicate whether or not the movie clip is 
    	 * currently playing.  Have your classes extend this
    	 * class instead of MovieClip or set this class as the
    	 * Base class of your movie clip(s) in the library to
    	 * have those instances gain the isPlaying property.
    	 */
    	public class MovieClipWithIsPlaying extends MovieClip {
    		
    		/**
    		 * Private property to internally keep track of whether or
    		 * not the current movie clip is being played
    		 */
    		private var _isPlaying:Boolean = true;
    			
    		/**
    		 * Getter function creating a public, read-only isPlaying
    		 * property allowing users to get but not set the _isPlaying
    		 *  property to determine if the movie clip is playing
    		 */
    		public function get isPlaying():Boolean {
    			return _isPlaying;
    		}
    		
    		/** 
    		 * Constructor
    		 */
    		public function MovieClipWithIsPlaying(){
    			super();
    		}
    		
    		// override all timeline commands for movie clip that would
    		// affect the isPlaying property of the movie clip:
    		
    		public override function gotoAndPlay(frame:Object, scene:String = null):void {
    			_isPlaying = true;
    			super.gotoAndPlay(frame, scene);
    		}
    		
    		public override function gotoAndStop(frame:Object, scene:String = null):void {
    			_isPlaying = false;
    			super.gotoAndStop(frame, scene);
    		}
    		
    		public override function nextFrame():void {
    			_isPlaying = false;
    			super.nextFrame();
    		}
    		
    		public override function nextScene():void {
    			_isPlaying = true;
    			super.nextScene();
    		}
    		
    		public override function play():void {
    			_isPlaying = true;
    			super.play();
    		}
    		
    		public override function prevFrame():void {
    			_isPlaying = false;
    			super.prevFrame();
    		}
    		
    		public override function prevScene():void {
    			_isPlaying = true;
    			super.prevScene();
    		}
    		
    		public override function stop():void {
    			_isPlaying = false;
    			super.stop();
    		}
    	}
    }
    Saved as MovieClipWithIsPlaying.as in a folder within your FLA's class path (such as the same folder your FLA exists) and added as the base class as your movie clip symbols in your library (using the class name MovieClipWithIsPlaying) your symbol instances now gain a isPlaying property indicating whether or not the movie clip is stopped or playing. Example:
    Code:
    if (myMovie.isPlaying) {
    	myMovie.stop();
    }

  14. #329
    Hello Senocular,

    What happens to the "ADDED" and "REMOVED" events. Should they be removed also?

    I was thinking about making a base Sprite class that removes all added Events uppon removal, then use this base class for all my Sprite objects. Would that make sense?

  15. #330
    Quote Originally Posted by pietheyn View Post
    Hello Senocular,

    What happens to the "ADDED" and "REMOVED" events. Should they be removed also?

    I was thinking about making a base Sprite class that removes all added Events uppon removal, then use this base class for all my Sprite objects. Would that make sense?
    You mean you want to stop them from happening?

Page 22 of 45 FirstFirst ... 12202122232432 ... LastLast

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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

Home About kirupa.com Meet the Moderators Advertise

 Link to Us

 Credits

Copyright 1999 - 2012