The forums have permanently moved to forum.kirupa.com. This forum will be kept around in read-only mode for archival purposes. To learn how to continue using your existing account on the new forums, check out this thread.


Page 24 of 45 FirstFirst ... 14222324252634 ... LastLast
Results 346 to 360 of 669

Thread: ActionScript 3 Tip of the Day

  1. #346
    Quote Originally Posted by senocular View Post
    You mean you want to stop them from happening?
    Yes, stop them from happening. The base Sprite class I was talking about would have a event listener on "REMOVED", loop all the events it's listening to and do a removeEvent for those events.
    Last edited by pietheyn; April 22nd, 2007 at 05:02 AM.

  2. #347
    120
    posts
    Registered User
    Okay so let me get this straight, the package command can't be used in .fla?
    Like you would normally do with 2.0 you would open the first frame in actions and start coding. You can't use package there?

    I read a bit more about it but I don't understand why would I want to use so much classes in different .as files instead of function for example? Doesn't it just get really confusing

    Can someone give me like some solid example of some simple program where they have 2 files the .as and .fla?
    Last edited by hatu; April 22nd, 2007 at 11:31 AM.

  3. #348
    Quote Originally Posted by pietheyn View Post
    Yes, stop them from happening. The base Sprite class I was talking about would have a event listener on "REMOVED", loop all the events it's listening to and do a removeEvent for those events.
    It wouldnt be doing a "removeEvent," theres no real way to know what was added or removed or whats currently listening (unless manually keeping track each time a new listener was added). Instead you'd probably just stop propagation to prevent the event from reaching a listener. For that you would have something like...
    Code:
    package {
    	
    	import flash.display.Sprite;
    	import flash.events.Event;
    	
    	public class CustomSprite extends Sprite {
    		
    		public function CustomSprite(){
    			// listen during capture phase with highest priority
    			addEventListener(Event.ADDED, stopEvent, true, 2147483647, true);
    		}
    		
    		private function stopEvent(event:Event):void {
    			event.stopImmediatePropagation();
    		}
    	}
    }
    And you would add listener with any event type (with stopEvent) that you wanted to prevent reaching CustomSprite instances (subclasses).

  4. #349
    Quote Originally Posted by hatu View Post
    Okay so let me get this straight, the package command can't be used in .fla?
    Like you would normally do with 2.0 you would open the first frame in actions and start coding. You can't use package there?

    I read a bit more about it but I don't understand why would I want to use so much classes in different .as files instead of function for example? Doesn't it just get really confusing

    Can someone give me like some solid example of some simple program where they have 2 files the .as and .fla?
    The package command is for AS files only. It defines that package, or path of that file on your system (which reflects its location in code). In the FLA, everything is internal and automatically generated (class files are created by Flash itself based on your timeline script) in an empty package. This is equivalent to having an AS file defined with a package of "package { ... }". You have no control over how Flash does this as its all hidden from the user to make things easier for people not wanting to deal with classes. If you want to manage package definitions, then you would define the classes yourself in your own AS files. (there should be one or two tip posts that cover packages and auto class code generation from flash)

    The point of having a bunch of external class files is that you are separating complex code into larger more managable "chunks" or objects. Each class file represents an object that will ultimately simplify your movie (or application or game, or whatever).

    For example. Lets say you're making a shooting game. You could go through and define all these functions in your movie and make a mess of code on the main timeline, or you could break that code up into its basic parts and define each of them as a class in their own class file giving you manageable, easy-to-work-with objects. This will let you program a game that looks more like this:
    Code:
    var game:ShooterGame = new ShooterGame();
    game.playerShip = new ZWing();
    game.currentLevel = new Level(1);
    game.start();
    Where ShooterGame, ZWing and Level are all classes (defined in their own AS files) that have their own internal workings, but are not defined in this part of the code. This makes this code simpler and easier to read where you just look at the objects and go "Yeah, I know that ZWing will be a space ship and can do cool things, but I don't have to worry about how right now, just that my game needs the player to have a space ship and this is the one he's getting". The details of that space ship are in the ZWing AS file and if you need to modify or define that definition that's where you go.

    The AS files provide organization. Similarly, packages provide ways to orgainze those AS files (classes) into their own folders, which, as I said before, is reflected in code. So if your ZWing class is defined in the my.classes package, its actual definition in ActionScript is my.classes.ZWing. That in code is a reference to the class. To keep you from typing that every time you want to use that class, Flash provides the import command which shortens that name to just ZWing (in AS2 import *only* shortened class names, in AS3, it is also needed to indicate that you are going to be using the class - note Flash will automatically import classes inherent to Flash and the Flash player so you won't have to use the import command to import each of them when used in Flash).

  5. #350
    Quote Originally Posted by senocular View Post
    The _root and _global objects in ActionScript 2 were globally accessible in code (meaning they could be accessed anywhere) making them easy places to store variables and functions to be used anywhere else. In ActionScript 3, there is no longer a _global object, and _root, now root, is accessible only to DisplayObject instances and only to those currently on the screen in an active display list. This makes them very difficult to use to store definitions that you want accessible everywhere. Instead, now with AS3, what you would need to do is use classes.

    More specifically, static variables in classes...
    That's a good tip.. I've been doing just the opposite (passing properties of a Main class to methods of other classes). I think I'll give this approach a try in my next project..

    Thanks again for all these, senocular..

  6. #351
    Quote Originally Posted by Pattt View Post
    Omg! AS3 is huge. And the CS3 AS is so different.
    Where can I get started with the CS3 AS3?
    Here's a blog post on getting started with AS 3.0

  7. #352

    Fla Script Flash CS3: Changing Function Behavior Across Frames

    Because all named functions defined on the timeline in ActionScript 3 become methods of the class that make up the movie clip representing that timeline, you cannot redefine a named function with the same name on another frame to give it different functionality.
    Code:
    // Frame 1
    function myFunction():void {
         // code...
    }
    
    // Frame 2
    function myFunction():void {
         // different code...
    }
    Doing so will resultin the following error:
    1021: Duplicate function definition.
    In order to get around this, you will need to define your functions as anonymous functions defined in a Function variable. This will use a variable within the timeline's class that can be redefined as opposed to an otherwise static function definition.
    Code:
    // Frame 1
    // declare class variable
    var myFunction:Function;
    
    // first definiton
    myFunction = function():void {
         // code...
    }
    
    // Frame 2
    // second definition
    myFunction = function():void {
         // different code...
    }

  8. #353

    Fla Script No more random(); Use Math.random()

    The random() function in ActionScript has been deprecated since Flash 5. Since then, the command has continued to exist within the ActionScript language though it has always been a best practices to use Math.random() instead. In ActionScript 3, random() has been completely removed. For random numbers you will need to now use Math.random();

    Like random(), Math.random() is used to produce random numbers, however it functions slightly differently. Instead of providing a whole number between 0 and up to but not including the number you pass into random(), Math.random() instead returns a random decimal value between 0 and 1 without any need to pass it any value. If you want to have Math.random behave like random, you need to use the following command where n is the number you would have passed into a call to random();
    Code:
    Math.floor(Math.random()*n); // = random(n)

  9. #354

    Fla Script LivePreview and the LivePreviewParent class

    For components in ActionScript 2, you could determine if your component was being displayed in the Flash IDE as a live preview of your component using an isLivePreview property (defined in _global). This property no longer exists in ActionScript 3. Instead, you can check to see if your component is being played as a live preview by checking to see if it's parent is an instance of the LivePreviewParent class.

    Code:
    var isLivePreview:Boolean = (parent != null && getQualifiedClassName(parent) == "fl.livepreview::LivePreviewParent");

  10. #355

    Fla Script Loading External SWFs with Loader (Preloading)

    When loading external movies or other display content (like images) into the Flash Player with ActionScript 3, you load the content into a Loader instance. Loaders provide containers for the external content to exist. No longer can you load external content into any movie clip, nor can you load SWFs into another level as levels no longer exist in ActionScript 3; you have to use a Loader instance.

    You create Loader instances just like you create any other display object and add it to a display list using addChild(). To load content into the Loader you use Loader.load() passing in a URLRequest object containing the url of your content.

    All DisplayObject instances have a loaderInfo property consisting of a LoaderInfo instance that provides information about that object's loaded content (if applicable). The Loader instance contains this property along with an additional contentLoaderInfo property which represents the LoaderInfo instance of the content being loaded. When loading content into a Loader, the contentLoaderInfo property is the object you would want to add listeners to for information about the loaded content such as when new bytes are being loaded into the player (for a preloader) and when loading has completed.

    The events associated with LoaderInfo instances includes:
    • complete:Event — Dispatched by the associated LoaderInfo object when the file has completed loading. The complete event is always dispatched after the init event.
    • httpStatus:HTTPStatusEvent — Dispatched by the associated LoaderInfo object when a network request is made over HTTP and Flash Player can detect the HTTP status code.
    • init:Event — Dispatched by the associated LoaderInfo object when the properties and methods of the loaded SWF file are accessible. The init event always precedes the complete event.
    • ioError:IOErrorEvent — Dispatched by the associated LoaderInfo object when an input or output error occurs that causes a load operation to fail.
    • open:Event — Dispatched by the associated LoaderInfo object when the loading operation starts.
    • progress:ProgressEvent — Dispatched by the associated LoaderInfo object as data is received while load operation progresses.
    • unload:Event — Dispatched by the associated LoaderInfo object when a loaded object is removed.


    Simple implementation:
    Code:
    var request:URLRequest = new URLRequest("content.swf");
    var loader:Loader = new Loader();
    loader.load(request);
    addChild(loader);
    The above example will blindly load content.swf within the loader instance. When/if the content has been successfully loaded, it will be displayed within the Loader instance which, since it has been added to the display list will be visible on the screen.

    Loading with Error checking:
    Code:
    var request:URLRequest = new URLRequest("content.swf");
    var loader:Loader = new Loader();
    
    loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, ioError);
    function ioError(event:IOErrorEvent):void {
    	trace(event);
    }
    
    try {
    	loader.load(request);
    }catch (error:SecurityError) {
    	trace(error);
    }
    
    addChild(loader);
    Here error checking is applied to determine if there were any errors with the loading process. The first check is the ioError listener associated with the contentLoaderInfo property of the Loader instance catching any input or output errors assocated with the content being loaded. Note that the listener was added to contentLoaderInfo and not the loader itself.

    The second check is the try-catch block used with the load() operation. The load method of Loader will throw SecurityError errors if:
    • The value of LoaderContext.securityDomain must be either null or SecurityDomain.currentDomain. This reflects the fact that you can only place the loaded media in its natural security sandbox or your own (the latter requires a policy file).
    • Local SWF files may not set LoaderContext.securityDomain to anything other than null. It is not permitted to import non-local media into a local sandbox, or to place other local media in anything other than its natural sandbox.
    • If the applicationDomain or securityDomain properties of the context parameter are from a disallowed domain.
    • If a local SWF file is attempting to use the securityDomain property of the context parameter.


    It is recommended that you always check for errors, especially synchronous (thrown) errors since whenever an error is thrown, the current script block is exited leaving the remaining script unexecuted. Also, if the viewer is playing the movie in the debug version of the Flash Player, uncaught exceptions, both thrown and asynchronous errors (those handled by listeners) will appear in a pop-up dialog.

    Loading with Preloader:
    Code:
    var request:URLRequest = new URLRequest("content.swf");
    var loader:Loader = new Loader();
    
    loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loadProgress);
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
    
    function loadProgress(event:ProgressEvent):void {
    	var percentLoaded:Number = event.bytesLoaded/event.bytesTotal;
    	percentLoaded = Math.round(percentLoaded * 100);
    	trace("Loading: "+percentLoaded+"%");
    }
    function loadComplete(event:Event):void {
    	trace("Complete");
    }
    
    loader.load(request);
    addChild(loader);
    Again, here, the contentLoaderInfo property is used to attach listeners. For preloading the PROGRESS event is used to obtain information about the loading progress. When completed, the COMPLETE event is dispatched. Traces are used in this example but an alternate preloader animation or visual can be adjusted within the PROGRESS event handler to visiually indicate the progression of the download.

    Error checking was omitted from the above example for clarity but should always be used.

  11. #356

    Fla Script Flex Component Kit for Flash CS3

    The Flex Component Kit for Flash CS3 (currently on Adobe Labs) "allows you to create interactive, animated content in Flash, and use it in Flex as a Flex component."

    From Matt Chotin:
    Flash content can now easily be a first-class citizen in a Flex application. Simply have your Flash symbol extend our new UIMovieClip class and you're ready to go. Some highlights:

    • Flash components can live in a Flex container and all layout will work
    • Flash component frame labels are integrated into the Flex state and transition system
    • Flex Builder will code-hint properly for your Flash component, simply add the SWC to your library path
    • Simple JSFL commands are available to set up new documents as well as publish the Flex-enabled SWC
    You can view a presentation by Glenn Ruehle showing off the component kit along with some examples:
    http://adobedev.adobe.acrobat.com/p75214263/

  12. #357

    Fla Script Flash CS3: New Library BitmapData Instances

    When you create a new MovieClip instance from your library, you create a new instance of the class provided for that movie clip symbol in its Linkage settings. If you have not defined that class yourself, Flash will create one automatically (subclassing MovieClip).
    Code:
    var myMovieClip:MovieClip = new CustomSymbol();
    (Note: Since CustomSymbol is a subclass of MovieClip, myMovieClip can be typed as MovieClip instead of CustomSymbol; same applies to the BitmapData example below)

    You can also set a class for bitmap images within your library. When you instantiate these instances in code based on the class name provided in the Linkage settings, you get an instance of a BitmapData class (or a subclass of BitmapData; Flash also automatically generating a class if one was not explicitly provided by you). Unlike MovieClip, however, the BitmapData class requires 2 of its parameters to be included for new instances, width and height.
    BitmapData signature:
    Code:
    public function BitmapData(width:int, height:int, transparent:Boolean = true, fillColor:uint = 0xFFFFFFFF)
    As a result, classes automatically generated by Flash to represent your BitmapData instances from images in your library will also require those two parameters. What you provide for these parameters, however, will not affect the final image. The size of the BitmapData instance created will be based off of the image in the library. Consider an image in the library with an automatic class name of MyImage. In ActionScript you would create a new instance of this image (as a BitmapData instance) using new MyImage passing in the required width and height properties
    Code:
    var image:BitmapData = new MyImage(10, 10); // required width and height
    trace(image.width, image.height); // 200 160
    Notice the actual width and height of the instance are based on the actual image in the library, not the values passed into the constructor. If you don't know the actual size of the image you are creating, you could use 0 for the width and height to imply the size being automatically generated by Flash from the image in the library.

    If you were to create a custom subclass for the image yourself, the same would apply with the call to super within your class's constructor. You will need to pass the required width and height arguments into super so that the BitmapData constructor will receive them. As with the automatic class, the values passed will be ignored and the actual image's size will be used. In using a custom class, though, you can prevent the need to pass the width and height into the constructor of your new instance if you do not require them in your class definition
    Code:
    // MyImage.as
    package {
    	import flash.display.BitmapData;
    	public class MyImage extends BitmapData {
    		public function MyImage(){
    			super(0,0); // size will automatically be determined
    		}
    	}
    }
    Code:
    // FLA
    var image:BitmapData = new MyImage(); // width and height not required
    trace(image.width, image.height); // 200 160
    Because the image instance in this example is a BitmapData instance, it needs to be added to a Bitmap instance to be displayed on the screen.
    Code:
    addChild(new Bitmap(image));

  13. #358

    Fla Script Flash CS3: Frame Navigation and Child Access

    ActionScript with version 3.0 is now entirely class based. Before, there was a heavy integration with the timeline and ActionScript - in fact, all classes defined in ActionScript 1 and 2 were defined on the main timeline as timeline code, not as separate class entities. Because of this new restructuring of ActionScript and this separation from the timeline, there has been a substantial change in how ActionScript interacts with the timeline and frame navigation. A specific example revolves around navigating to a new frame within a movie clip and then accessing child objects within that frame. In ActionScript 2, this could easily be achieved with the following:
    Code:
    // ActionScript 2.0
    target.gotoAndStop(10);
    target.child._rotation = 90;
    Where the child movie clip is a movie clip on frame 10 of the target movie clip. Using target.child._rotation = 90; that child movie clip could be rotated to 90 degrees.

    This is no longer possible in ActionScript 3.

    At least not as easily. The child objects that exist within a newly navigated frame are not instantiated until after the completion of the frame script. This prevents any unnecessary instantiation of objects in the case that later within that same frame script the object was told to go to a different frame. The downside of this is that no longer will you be able to directly access children in that frame directly after navigating to it as you could before. Now you have to wait until they are instantiated before being able to do anything with them.

    The following outlines the order of execution within a frame's time where a target movie clip is navigated to a frame within its timeline where one or more child movie clips exist and would need to be accessed.

    1. Event.ENTER_FRAME event
    2. target parents' frame scripts
    3. target's sibling objects' frame scripts for objects arranged below target
    4. target frame script [where frame navigation presumably occurs]
    5. Instantiation of each target's child objects in new frame
    6. Event.ADDED event for each target's child objects in new frame
    7. assignment of target's instance name properties for children in new frame
    8. target's sibling objects' frame scripts for objects arranged above target
    9. Event.RENDER event (requires call to stage.invalidate())
    10. Flash draws screen

    Note: sibling objects refer to objects with the same parent as the target instance

    The main thing to take away from this order is that the instatiation and addition of the child objects within the target instance doesn't occur until after the current frame script of that target completes. This leaves you no way to access those children within that script directly. What you would need to do is access those children through the ADDED or RENDER events. And when using the ADDED event, you still can't reference the children by their instances names as with the AS2 example since the instance name assignment doesn't occur until after the ADDED event(s) complete. For the ADDED events, you would need to check the Event.target property in the event handler and see if the name of that target matches the instance name of the object you wish to access. Using the render event is a little easier but requires a call to stage.invalidate() to even be dispatched.

    Using the ADDED Event:
    Code:
    // ActionScript 3.0
    // add an ADDED event handler to the movie clip
    // whose frames are being navigated and whose
    // child needs to be accessed
    target.addEventListener(Event.ADDED, onAdded);
    function onAdded(event:Event):void {
    	// get reference to child from event object
    	// as child variable of target will not yet be defined
    	var childRef:MovieClip = event.target as MovieClip;
    	
    	// check the name of the reference for correct instance name
    	if (childRef && childRef.name == "child"){
    		childRef.rotation = 90;
    		target.removeEventListener(Event.ADDED, onAdded);
    	}
    }
    target.gotoAndStop(10);
    Using the RENDER Event:
    Code:
    // ActionScript 3.0
    // add an RENDER event handler to the movie clip
    // whose frames are being navigated and whose
    // child needs to be accessed
    target.addEventListener(Event.RENDER, onRender);
    function onRender(event:Event):void {
    	// by the time the RENDER event fires, the child
    	// clip will be completely defined and accessible
    	target.child.rotation = 90;
    }
    
    // for RENDER to be dispatched, the stage
    // has to be invalidated
    stage.invalidate();
    target.gotoAndStop(2);
    Because of this complication, it would be wise to design your applications/Flash movies so that you would not have to access child objects in this manner if possible.

  14. #359

    Fla Script Loading URL encoded Variables

    The URLLoader class (flash.net.URLLoader) in ActionScript 3 is used to load content from an external text file. When an external file has been loaded, its contents are stored within the data property of the URLLoader instance. Normally, the contents of a file, no matter what the file is, is loaded in as raw text. If you want the contents of a file to be loaded as variables (i.e. the loaded file is a text file whose contents consist of URL-encoded variables) then you will want to change the dataFormat property of the URLLoader.

    The dataFormat property determines the format of the data being loaded into the URLLoader. Values for dataFormat are contained within the URLLoaderDataFormat class (flash.net.URLLoaderDataFormat). Possible values include:
    • BINARY - Specifies that downloaded data is received as raw binary data.
    • TEXT - Specifies that downloaded data is received as text.
    • VARIABLES - Specifies that downloaded data is received as URL-encoded variables.

    Using URLLoaderDataFormat.VARIABLES for the URLLoader's dataFormat, the loaded data will come in as a collection of variables instead of a string. The value of the data property will then be a URLVariables class (flash.net.URLVariables) instance whose properties consist of the variables loaded.

    Code:
    var loader:URLLoader = new URLLoader();
    
    // specify format as being variables
    loader.dataFormat = URLLoaderDataFormat.VARIABLES;
    
    loader.addEventListener(Event.COMPLETE, varsLoaded);
    
    // vars.txt contents:  foo=bar&foo2=bar2
    loader.load(new URLRequest("vars.txt")); 
    
    function varsLoaded (event:Event):void {
    	trace(loader.data is URLVariables); // true
    	trace(loader.data.foo); // bar
    	trace(loader.data.foo2); // bar2
    }

  15. #360

    Fla Script Interactive Masks

    By default, when you assign an object to be the mask of another object, that object (the mask) loses its interactivity. For example, a sprite with a click event associated with it will recieve those events when not a mask but will not be able to once it becomes a mask.

    If you want an object acting as a mask to be interactive, assign its buttonMode property to be true.
    Code:
    maskInstance.buttonMode = true;

Page 24 of 45 FirstFirst ... 14222324252634 ... LastLast

Thread Information

Users Browsing this Thread

There are currently 3 users browsing this thread. (0 members and 3 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