Archive for the ‘ActionScript 3’ Category

Difference between MouseEvent.ROLL_OVER and MouseEvent.MOUSE_OVER in AS3

Thursday, June 19th, 2008

This was a question that has been in my head for a long time: what is the difference between MouseEvent.ROLL_OVER and MouseEvent.MOUSE_OVER. I have been using MouseEvent.MOUSE_OVER for all my rollOvers up to now without really thinking about it, but I think it would be interesting to know the difference for something so basic.

If you look at the documentation that comes with Flash CS3. You will find very little help. There are no examples explaining the difference between the two. The only difference you will find there is that the MOUSE_OVER event has the bubbles property set to true and the ROLL_OVER to false. I don’t know how much that property impacts on the behavior of the event, but I am keeping event bubbling for another post (I have been postponing that post for a long time).

Where I found there was a difference between the two events is in the way they handle children of the display object you added the listener too. I have made a simple example to show this:

In that flash example, be sure to roll over the blue part of the button to really see the difference(note that the blue rectangle is inside the black rectangle movieClip, not just over). In the MOUSE_OVER example, the event is fired for every children of the display object that the listener was added to. This does not happen with the ROLL_OVER event. If you move your mouse from the exterior of the button to the blue part MOUSE_OVER will generate 3 times the events that ROLL_OVER will. One way to make MOUSE_OVER act as ROLL_OVER is to set mouseChildren = false but as a consequences: the first is that it will disable all mouse events from children which I think might help the CPU but at the same time you won’t be able to interact with the children with the mouse.

In our previous example, it didn’t really matter how many events where fired because we used a tween to do the rollover and we weren’t able to see the difference visually, but there might be times where you will want all the different events. Like if you want the mouse cursor to change when over a movieClip and still want rollOver effects from children of that movieClip, you would use the MouseEvent.ROLL_OVER to change the mouse cursor and MouseEvent.MOUSE_OVER for the children movieClips rollOver effects.

As a side note on cpu efficiency, it doesn’t really matter if you listen to  MouseEvent.ROLL_OVER or MouseEvent.MOUSE_OVER events, they are both as efficient. What will save you cpu cycles is if you disable the children of a movieClip from sending events if you don’t need them (even if you don’t listen to them events are still fired) using mouseChildren =  false.

I hope this shed some light on the subject.

My intermediate Flash presentation

Saturday, May 17th, 2008

Where I work we have these kind of workshops that are given by the employees. I was mandated to give a presentation entitled Advanced Flash, but it is not really going to be advanced; more like intermediate. I am basically going to introduce ActionScript 3, Tweening using TweenLite, Events, Linking symbol to a class, using the document class, loading an image, loading an XML and maybe speak about setIntervals and setTimeout versus Timer. I thought I would make this blog post my actual presentation notes so that it would help also people reading my blog.

My objective after this workshop is that the people attending it will be able to open Flash files I did using ActionScript 3 and find what they are looking for and also understand mostly the mechanics in the project. I did the presentation on May 13th and it went well for the most part, the biggest trouble was because we where on a projector with a resolution of 1024x768 and I am used to have 2 22 inch monitors (I hate the way Flash CS3 handles its panels).

Difference between ActionScript 2 and 3

First I want to mention difference between ActionScript 2 and 3. Mostly in the properties of a MovieClip, there used to be properties called _x, _y, _rotation, _visible, _alpha, _width, _height. Now these properties have been renamed to x, y, rotation, visible, alpha, width, height. The alpha property now goes from 0 to 1 instead of 0 to 100. If you want an alpha of 60% you do this: alpha = 0.6. Last thing, you cannot put ActionScript on MovieClip anymore, only on a frame in the timeline or in a class (external AS file). This will help prevent searching for ActionScript code for hours.

I am used to MovieClip, but what are Sprites?

Sprites are just a toned down version of a MovieClip. Sprites don't have timelines, so you can't use function like gotoAndPlay() and stop(). Why use them? Well since they don't have a timeline and the timeline associated functions they also take less memory, so they should always be used whenever you don't need the timeline. More on Sprites later.

Making things move, TweenLite for everything

One of the biggest building block in all of my projects is TweenLite. Nearly every swf or external class I use will have TweenLite in it. Here is a tutorial on how to use TweenLite. If you run one of my swf files if something moves it has 90% chance that TweenLite is making it move. I also use it for fade in, fade out transitions, button rollovers and music fade out.

Actionscript:
  1. TweenLite.to(rectangle, 1.5, {x:300, y:300, alpha:50, tint:0x0000ff});

A simple button using Sprites

Here is how I would do a simple button using Sprites and TweenLite. First draw a rectangle on the stage. Then convert it to a symbol, click export for ActionScript, in the base class field put flash.display.Sprite instead of flash.display.MovieClip. That is how you can create Sprites using Flash CS3. Now give the newly created Sprite a variable name of rectangle. Put the following code on the first frame on your movie (you will have to have downloaded TweenLite before you can do this):

Actionscript:
  1. import gs.TweenLite;
  2.  
  3. rectangle.buttonMode = true;
  4. rectangle.mouseChildren = false;
  5.  
  6. rectangle.addEventListener(MouseEvent.MOUSE_OVER, handleMouseOver);
  7. rectangle.addEventListener(MouseEvent.MOUSE_OUT, handleMouseOut);
  8. rectangle.addEventListener(MouseEvent.MOUSE_DOWN, handleMouseDown);
  9.  
  10. function handleMouseOver(event:MouseEvent):void{
  11.   TweenLite.to(rectangle, 0.5, {tint:0xFF0000});
  12. }
  13.  
  14. function handleMouseOut(event:MouseEvent):void{
  15.   TweenLite.to(rectangle, 0.5, {tint:0x0000FF});
  16. }
  17.  
  18. function handleMouseDown(event:MouseEvent):void{
  19.   trace ("this is the mouse down event");
  20. }

This method works fine in most cases but when you have multiple buttons, you have to copy and paste all 14 previous line of code and that makes a lot of overhead. That is exactly why we use classes.

Taking that simple button and make it a class

The following code is exactly like the code we put on the timeline before but written as a class:

Actionscript:
  1. package net.zedia{
  2.   import flash.display.Sprite;
  3.   import flash.events.MouseEvent;
  4.   import gs.TweenLite;
  5.  
  6.   public class MySimpleButton extends Sprite{
  7.     public function MySimpleButton(){
  8.       buttonMode = true;
  9.       mouseChildren = false;
  10.       addEventListener(MouseEvent.MOUSE_OVER, handleMouseOver);
  11.       addEventListener(MouseEvent.MOUSE_OUT, handleMouseOut);
  12.     }
  13.  
  14.     private function handleMouseOver(event:MouseEvent):void{
  15.       TweenLite.to(this, 0.5, {tint:0xFF0000});
  16.     }
  17.  
  18.     private function handleMouseOut(event:MouseEvent):void{
  19.       TweenLite.to(this, 0.5, {tint:0x0000FF});
  20.     }
  21.   }
  22. }

Here is how you would then use this class :

Actionscript:
  1. import net.zedia.MySimpleButton;
  2.  
  3. var mySimpleButton1:MySimpleButton = new MySimpleButton();
  4. var mySimpleButton2:MySimpleButton = new MySimpleButton();
  5.  
  6. mySimpleButton2.y = 100;
  7.  
  8. addChild(mySimpleButton1);
  9. addChild(mySimpleButton2);

In this example both buttons will have rollOvers and rollOut implemented.

Document class where is it?

Actionscript:
  1. package {
  2.   import flash.display.Sprite;
  3.   public class Main extends Sprite {
  4.     public function Main(){
  5.     }
  6.   }
  7. }

Loading an image

Loading an image is quite simple, you have to use a class named Loader which is a DisplayObject. Just as for the button, you have to add a listener to the object to know when the file as totally loaded. Loader are special in the way that you don't attach the listener directly to the Object. You do it like this: myLoader.contentLoaderInfo.addEventListener. The Loader is the only class that behaves this way.

Actionscript:
  1. import flash.display.Loader;
  2. import flash.events.Event;
  3. import flash.net.URLRequest;
  4.  
  5. var myLoader:Loader = new Loader();
  6. myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, handleInit);
  7. myLoader.load(new URLRequest("slide1.png"));
  8.  
  9. function handleInit(e:Event):void{
  10.   addChild(myLoader.content);
  11. }

Loading a XML

Loading an XML is similar to loading an image except that you use the URLLoader class instead of the Loader class. The URLLoader class doesn't have the weird event behavior so you attach the listener directly to the object.

Actionscript:
  1. import flash.net.URLLoader;
  2. import flash.net.URLRequest;
  3. import flash.events.Event;
  4.  
  5. var XMLLoader:URLLoader;
  6.  
  7. XMLLoader = new URLLoader(new URLRequest("myXML.xml"));
  8. XMLLoader.addEventListener(Event.COMPLETE, handleLoadedXml);
  9.  
  10. function handleLoadedXml(event:Event):void{
  11.   var xml:XML = new XML(event.target.data); // or var xml:XML = new XML(XMLLoader.data)
  12.   trace (xml.rooms.room[0]);
  13. }

Preloading

Preloading a swf file or an image is exactly the same thing. I always make my preloader external to the file I am loading. There is another way of doing this by doing the preloader in the first 2 frames of a swf file. The advantage of doing an external preloader is that it will start at zero if you exported symbols in the library for ActionScript. Basically we take the code we had for loading an image and we add the listener and the handler function for the PROGRESS event.

Actionscript:
  1. import flash.display.Loader;
  2. import flash.display.Event;
  3.  
  4. var myLoader:Loader = new Loader();
  5. myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, handleInit);
  6. myLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, handleProgress);
  7. myLoader.load(new URLRequest("main.swf"));
  8.  
  9. function handleProgress(event:ProgressEvent):void{
  10.   var percent:Number = Math.round(e.bytesLoaded / e.bytesTotal * 100)
  11.   trace (percent);
  12. }
  13.  
  14. function handleInit(e:Event):void{
  15.   addChild(myLoader.content);
  16. }

setIntervals and setTimeout VS Timer or TweenLite.delayedCall

In ActionScript 3 it is not good practice to use setIntervals and setTimeouts but they are still available if you really need them. It is better to use the Timer class, but I never really use it, instead I use TweenLite to make stuff move, ENTER_FRAME for setIntervals and TweenLite.delayedCall for setTimeouts. Here is an example of how to use TweenLite.delayedCall:

Actionscript:
  1. import gs.TweenLite;
  2.  
  3. TweenLite.delayedCall(3, startAnim);
  4.  
  5. function startAnim():void{
  6.   trace ("animation started");
  7. }
  8.  
  9. TweenLite.killDelayedCallsTo(startAnim);

generate random Strings in AS2 or AS3

Saturday, May 10th, 2008

I was searching for a function to generate random Strings either in AS2 or in AS3 but I couldn't find any so I made my own using code from a typewriter effect, but I can't seem to find the page anymore. I use this code when I load dynamic content from php and such and I don't want flash to cache my request. Here is an ActionScript 2 version of the code:

Actionscript:
  1. function generateRandomString(newLength:Number):String{
  2.   var a:String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  3.   var alphabet:Array = a.split("");
  4.   var randomLetter:String = "";
  5.   for (var i:Number = 0; i <newLength; i++){
  6.     randomLetter += alphabet[Math.floor(Math.random() * alphabet.length)];
  7.   }
  8.   return randomLetter;
  9. }

For the ActionScript 3 version of it I made some optimizations and I created a class with the static method in it here is the code:

Actionscript:
  1. package net.zedia.utils{
  2.   public final class StringUtils{
  3.     public static function generateRandomString(newLength:uint = 1, userAlphabet:String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"):String{
  4.       var alphabet:Array = userAlphabet.split("");
  5.       var alphabetLength:int = alphabet.length;
  6.       var randomLetters:String = "";
  7.       for (var i:uint = 0; i <newLength; i++){
  8.         randomLetters += alphabet[int(Math.floor(Math.random() * alphabetLength))];
  9.       }
  10.       return randomLetters;
  11.     }
  12.   }
  13. }

here is how you use it:

Actionscript:
  1. import net.zedia.utils.StringUtils;
  2.  
  3. trace (StringUtils.generateRandomString(4));//for a random string of 4 characters
  4.  
  5. trace (StringUtils.generateRandomString(4, "ROGER"));//for a random string of 4 characters using only the following letters: ROGER

Cet article en Français

BlendMode.LAYER; A must when changing the alpha property of a DisplayObject containing other DisplayObjects

Monday, April 28th, 2008

I don't know if you ever tweened a MovieClip's alpha while this MovieClip contained multiple assets, but I kinda do this all the time (fade in ,fade out being the easiest transition for almost everything). The default way Flash handles this is by changing the alpha of every assets in the containing MovieClip (or Sprite). Sometimes it doesn't matter but most of the time that's not the behavior you would like it to have. When you have shapes or bitmaps that overlap or hide other graphical assets you will see what is under it when changing the alpha instead of actually changing the alpha of the container as if it was a whole.

Well I don't know if it's clear but I have an example below that should clarify that. Anyway, I have stumbled upon the solution to this while browsing through the help files for BlendMode. If you set the blendMode of your containing DisplayObject to BlendMode.LAYER Flash will consider this DisplayObject as only one layer and will change the alpha the way you normally think it would.

Here is the example that will illustrate my point better. The left Sprite is the reference object, the middle Sprite has no blendMode on and the right Sprite has a blendMode of BlendMode.LAYER. Mostly look at the colors while tweening and the overlapping regions of the green and blue ellipses.

I really wish I had found this earlier and I hope this will help others that were in my situation.

Cet article en Français

Another good use of interfaces

Monday, April 14th, 2008

Earlier this year, I came to understand how to use interfaces in ActionScript 3. I used them in a particular case where polymorphism was needed but that was it since then. Last week I realized that I could use them in much more case than that. I actually need them in nearly all of my projects.

As I have mentioned in previous post, I always structure the websites I program in the same way. I make one swf file for the preloader, one swf file for the shell (container of navigation that load every sections) and one swf for every section (page) in the site. Sometimes, the preloader needs to inform the shell (main movie) when to start its intro animation. An example of that is the don't discover Loyalist contest website. When you first load the page, the flash file looks like it is just sitting there waiting for you to click on the start button. But actually it is already preloading the main swf file. That leads to two scenarios; either the user clicks on start and the main movie is not loaded yet so it will start only when it is fully loaded or the user clicks when the main swf is fully loaded and the preloader has to tell the main movie that it can start. I used to disable the strict mode of the compiler in order to call a public method of the main swf document class. That worked fine since I never have so much code involved for a preloader but then I hit a wall.

I came across the same problem when loading external Flash file from which I wanted to use methods. The compiler just didn't want me to do so. When I started coding in AS3, I, at first, found the compiler to be a bit severe, but I kinda like it now, it finds problems before they arise, so that's why I don't want to turn of strict mode for my main movie, where I have thousands of line of code. So I had to find another solution, I tried to import the document class of my external swf with an import statement but the compiler didn't like it that much because it wasn't finding classes for Sprites on the stage. That's when I remembered about interfaces.

Interfaces permit you to ensure that some classes contains some methods. So in my external swf document class I made certain it implemented the interface I was going to us and in my main movie I type casted the loader.content to that interface (Type).

Actionscript:
  1. import com.zedia.interfaces.ISection;
  2.  
  3. var mySection:ISection  = ISection(loader.content);

Now the compiler was happy. I could load external swf and use its methods. One trouble was left; I wasn't able to add my new content to the display list because my main movie didn't know that the external swf was extending a DisplayObject. All I had to do to solve this was to type cast my external swf to a Sprite when I added it to the display list like this:

Actionscript:
  1. addChild(Sprite(mySection)) ;

That really did the trick and now I am going to use interfaces in most of my projects.

Fading out volume using TweenLite

Monday, April 7th, 2008

I showed in my previous post how to change the volume of a playing sound. In this post I am going to show how to tween that volume using TweenLite.

The class we are going to do the tween on is the SoundTransform class. So we will first have to create our sound objects.

Actionscript:
  1. var someSound = new Sound(new URLRequest("MySound.mp3");
  2. var someChannel = new SoundChannel();
  3. var someTransform = new SoundTransform(1);//volume is set to the max
  4.  
  5. someChannel = someSound.play(0, 99999, someTransform);//The sound will start from 0 millisecond, will loop 99999 times and will use the someTransform SoundTransform
  6.  
  7. //the next lines are for fading out the volume
  8.  
  9. TweenLite.to(someSound, 1, {volume:0, onUpdate:updateChannel, onComplete:stopSound});
  10.  
  11. function updateChannel():void{
  12. someChannel.soundTransform = someTransform;
  13. }
  14.  
  15. function stopSound():void{
  16. someChannel.stop();
  17. }

As you can see, even if you modify the volume parameter of the SoundTranform it won't do a thing. You also have to update the SoundChannel. You can't also tween the SoundChannel.soundTransform.volume directly. It's the same as when you tween colors using Color.interpolateColor, you have to modify an intermidiate Object.

A little bit about Sound | Using the Sound, SoundChannel, SoundTransform classes

Monday, April 7th, 2008

I didn't really mess up with sounds in ActionScript 3 until recently. I can say that it changed a lot since ActionScript 2, it's a bit more complex, but I'm pretty sure it gives more possibilities also.

First, you can either load the sound from the library, or you can load it externally. If it is from the library, you first have to click export for ActionScript in the property panel from that sound, and use the class name you gave it. Let say you gave it "MySound" as class name here is how you would simply make it play:

Actionscript:
  1. var someSound:MySound =  new MySound();
  2. someSound.play();

If you want to load your sound from an external file it is a bit different but afterward it's all the same:

Actionscript:
  1. var someSound:Sound = new Sound(new URLRequest("MySound.mp3"));
  2. someSound.play();
  3.  
  4. //it could also be done like this
  5. var someSound:Sound = new Sound();
  6. someSound.load(new URLRequest("MySound.mp3"));
  7. someSound.play() ;

In the last example, the file MySound.mp3 has to be in the same folder as the HTML embedding the SWF because that what I indicate in the URLRequest.

If you use only the Sound class the only thing you can do is make the sound play, that's it, no stop, no pause, no adjustment to the volume. For that you will have to use two other classes SoundChannel and SoundTransform.

SoundChannel

The SoundChannel class possess only one method and it's the stop method. I guess you konw what it does. here is how you use it:

Actionscript:
  1. var someSound:Soundnew Sound(new URLRequest("MySound.mp3"));
  2. var someChannel:SoundChannel = new SoundChannel();
  3. someChannel = someSound.play();
  4. someChannel.stop();

The last bit of code is actually useless because it will stop the sound right after it started it but it is only to show how to use a SoundChannel. Fine but how do you pause a sound and than make it play again with only a stop() method? The SoundChannel class has a property called position which indicate where the play head is at. You have to save the value of the position property before calling the stop method. If you save to position property value after calling the stop method, it will be of value 0 which is of no interest. What you do with the value of the position property is you pass it as a parameter to the Sound.play() method. The first parameter, startTime, tell the Sound Object at which millisecond to start playing. It's a bit confusing but this example should make it clearer:

Actionscript:
  1. var someSound:Soundnew Sound(new URLRequest("MySound.mp3"));
  2. var someChannel:SoundChannel = new SoundChannel();
  3. var somePosition:Number;
  4.  
  5. someChannel = someSound.play();//this make the sound play
  6. somePosition = someChannel.position; //saves the value of the position property
  7. someChannel.stop(); //pause or stop the sound
  8. someChannel = someSound.play(somePosition);//this make the sound play but it now start from the position at which it was stopped

The Sound.play() method also takes two other optional parameters. The first of the two is the loops parameter, it indicate how many times you want the sound to play in loop. If you want your sound to loop forever you just pass a really big number as parameter. if you want it to play just once you pass it 0. The second of the two (the third parameter really) is the SoundTransform parameter.

SoundTransform

The SoundTransform class as some properties and no methods, but I will only speak about the volume property here. The volume property is a number ranging from 0 to 1, 0 being silent and 1 being at full volume. You can either set it in the constructor or after the SoundTransform has been created. here is how you would make a sound play at half the maximum volume:

Actionscript:
  1. var someSound:Soundnew Sound(new URLRequest("MySound.mp3"));
  2. var someChannel:SoundChannel = new SoundChannel();
  3. var someTransform:SoundTransfrom = new SoundTransform(0.5); // the 0.5 value here tells it to set volume to half the maximum value
  4.  
  5. someChannel = someSound.play(0, 0, someTransform);//the first 0 is startTime, the second is the number of loop, and finally we pass our SoundTransform

If we wanted to change the volume as the sound is playing we would do it in this way:

Actionscript:
  1. var someSound:Soundnew Sound(new URLRequest("MySound.mp3"));
  2. var someChannel:SoundChannel = new SoundChannel();
  3. var someTransform:SoundTransfrom = new SoundTransform(0.5); // the 0.5 value here tells it to set volume to half the maximum value
  4.  
  5. someChannel = someSound.play(0, 0, someTransform);
  6. someTransform.volume = 1;
  7. someChannel.soundTransform = someTransform;

This would start playing the the sound at half the volume to set it afterward at maximum volume. Well that is as far as I go with sound, with that you can do most of the common tasks. In a future post I will show how to use TweenLite to fade the volume to zero.

Converting a RGB color and Alpha to ARGB in ActionScript 3

Tuesday, March 25th, 2008

So I was using the color picker component that comes with the Flash IDE. When the user selects a color, the color picker fire a ColorPickerEvent.CHANGE event and from that event you can access the new color that was chosen. The format of this color is a uint; when working with colors I am more used to the hexadecimal format.  From the event you can also access to the hexdecimal value, but as a String which is not that useful if you want to do operation on the color.

The color you get from the color picker component is in the RGB format, so no transparency. If you want to add an alpha channel to that color (converting it to ARGB), let's say to use the setPixel32 method of the BitmapData class  and produce Bitmap with transparency, you're going to have to modify the uint you can do so using this simple function (AS3):

Actionscript:
  1. private function returnARGB(rgb:uint, newAlpha:uint):uint{
  2. //newAlpha has to be in the 0 to 255 range
  3. var argb:uint = 0;
  4. argb += (newAlpha&lt;&lt;24);
  5. argb += (rgb);
  6. return argb;
  7. }

What this function does is that it bit shift the value of the Alpha you input and adds it to the original RGB color making it ARGB. You see, RGB format uses 8 bits for each color for each pixel (so 24 bits for each pixel), when you add transparency, the alpha channel takes up another 8 bits for each pixels (making it 32 bits for each pixel thus the 32 in setPixel32). That also explains why newAlpha has to be from 0 to 255, because 255 is the highest number you can store in 8 bits. The Blue color takes the bits from 1 to 8, the Green color takes the bits from 9 to 16, Red from 17 to 24 and finally Alpha from 25 to 32. This is why we bit shift alpha from 24 bits (newAlpha<<24);

I don't use the color picker component often,

Mixing timeline and AS3; where are my global variables

Sunday, March 9th, 2008

Well using only ActionScript to do a website at my company is kind of a break in the workflow.  Before I came, only designers were doing the Flash websites so it was mostly timeline with ActionScript all over the place (meaning not so much ActionScript, but well spread over timeline, buttons and MovieClips). It's not what I believe the best way to work.

So we get this microsite to do; I can show it to you because it is online right now. It's Ski-Doo Spring Promotion. For this microsite we had a really tight deadline; 3 days to do design and production of the whole microsite. So I had to work very closely with the designer, which was good because he is really creative at doing animations. The trouble is that he does them timeline and I am used to doing only ActionScript websites... So I had to learn to mix both ways.

Every thing was going fine until I had to use global variables. I forgot to mention that we decided to do this project in ActionScript 3, in which there are no global variables anymore. My need for global variables was for data that was passed from the html to the flash, the country from which the user came and his language. So at first I was using the root.loaderInfo.parameters.country (as an example) as a global variable. I could, from any timeline anywhere in any movieclip, reference the parameters  had passed to the flash.

The trouble arose when I had to add an external preloader to the microsite. All of a sudden all my call to root.loaderInfo.parameters did not work anymore. I had to find another solution to my problem which I found in the GlobalVarContainer class from greenethumb. It is a really easy class to use and it did exactly what I wanted. You should go check it out.

I know using global variables is not a not a best practice; it's not modular and you can't safely reuse your code everywhere. But in this case, it really helped me mix the timeline animation workflow with the coding workflow.

The right way to do RollOver Event in AS3

Friday, February 8th, 2008

I have been asking myself this question for a long time now. I see two ways of doing a roll over using ActionScript 3. The first one is pretty straight foward and it is the one you've seen everywhere. Here is some sample AS3 showing how to do it:

Actionscript:
  1. button.addEventListener(MouseEvent.MOUSE_OVER, manageMouseOver);
  2. button.addEventListener(MouseEvent.MOUSE_OUT, manageMouseOut);
  3.  
  4. function manageMouseOver(e:MouseEvent):void{
  5.   //your over code here
  6. }
  7.  
  8. function manageMouseOut(e:MouseEvent):void{
  9.   //your out code here
  10. }

This is the classical way off doing thing. Doing it this way implies that for all your button you always have 2 listeners to do your rollovers. There is another way of doing this that will always use only one listener. Here it is

Actionscript:
  1. button.addEventListener(MouseEvent.MOUSE_OVER, manageMouseOver);
  2.  
  3. function manageMouseOver(e:MouseEvent):void{
  4.   button.removeEventListener(MouseEvent.MOUSE_OVER, manageMouseOver);
  5.   button.addEventListener(MouseEvent.MOUSE_OUT, manageMouseOut);
  6.   //your over code here
  7. }
  8.  
  9. function manageMouseOut(e:MouseEvent):void{
  10.   button.removeEventListener(MouseEvent.MOUSE_OUT, manageMouseOver);
  11.   button.addEventListener(MouseEvent.MOUSE_OVER, manageMouseOut);
  12.   //your out code here
  13. }

Doing it it this way, there will be less listener active at the same time, but each rollover will do 4 more actions. So is having less listeners worth doing more computations; is there situations where you should use one technique more than the other; or it has so little impact that we should not care about it?

I'd really like to know.


Close
E-mail It