Skip to Navigation | Skip to Content

AS3 Code Library and Sample Files

//Exploring circular movement

View .swf file: circularMotion.swf | Download .fla file: circularMotion.fla (right click and "Save Link As")

  1. //Exploring circular movement
  2. var myClip:MovieClip = new Clip(); //initialize clip from library
  3. addChild(myClip); //add it to the stage
  4. var angle:Number = 0; //configure variables
  5. var centerX:Number = stage.stageWidth/2;
  6. var centerY:Number = stage.stageHeight/2;
  7. var radiusX:Number = 100;
  8. var radiusY:Number = 100;
  9. var speed:Number = .1;
  10.  
  11. addEventListener(Event.ENTER_FRAME, onLoop);
  12. function onLoop(e:Event) {
  13.  
  14. //by changing the angle and using Math.sin for x and Math.cos for y, you can move in a circle
  15. myClip.x = centerX + Math.sin(angle) * radiusX;
  16. myClip.y = centerY + Math.cos(angle) * radiusY;
  17. angle += speed;
  18.  
  19. //move mouse to change radius
  20. radiusX = Math.abs(mouseX - stage.stageWidth/2);
  21. radiusY = Math.abs(mouseY - stage.stageHeight/2);
  22.  
  23. }

 

//Timer Event that counts down from 10 seconds

View .swf file: TimerEvents_CountDown.swf | Download .fla file: TimerEvents_CountDown.fla (right click and "Save Link As")

  1. //Timer Event that counts down from 10 seconds
  2. //Timer requires delay and repeat count
  3. //1000 = 1000 miliseconds, 10 = number of times to count
  4. var myTimer:Timer = new Timer(1000, 10);
  5. //tell the timer when to start
  6. myTimer.start();
  7. var myCount:int = 10;
  8. //listen for when the timer fires
  9. myTimer.addEventListener(TimerEvent.TIMER, onTimer);
  10. function onTimer(e:TimerEvent) {
  11. myCount--;
  12. //trace(myCount);
  13. time_txt.text = String(myCount);
  14. time_txt.x += 20;
  15. }
  16. myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, onDone);
  17. function onDone(e:TimerEvent) {
  18. time_txt.text = "Blast Off";
  19. }

 

//Keyboard Events and Input

View .swf file: KeyboardEvents.swf | Download .fla file: KeyboardEvents.fla (right click and "Save Link As")

  1. //Keyboard Events and Input
  2. stage.addEventListener(KeyboardEvent.KEY_DOWN, downKey);
  3. //stage.addEventListener(KeyboardEvent.KEY_UP, upKey);
  4. function downKey(e:KeyboardEvent) {
  5. trace("keycode: " + e.keyCode); //which key, A and a are on the same key
  6. trace("charcode: " + e.charCode); //which character, A and a are different
  7. trace (String.fromCharCode(e.charCode));
  8. trace("ctrlKey: " + e.ctrlKey);
  9. trace("keyLocation: " + e.keyLocation);
  10. trace("shiftKey: " + e.shiftKey);
  11. trace("altKey: " + e.altKey);
  12. switch (e.keyCode) {
  13. case Keyboard.UP:
  14. //case 38:
  15. box_mc.y -= 10;
  16. break;
  17. case Keyboard.DOWN:
  18. //case 40:
  19. box_mc.y += 10;
  20. break;
  21. case Keyboard.LEFT:
  22. //case 37:
  23. box_mc.x -= 10;
  24. break;
  25. case Keyboard.RIGHT:
  26. //case 39:
  27. box_mc.x += 10;
  28. break;
  29. case Keyboard.SPACE:
  30. trace ("space");
  31. break;
  32.  
  33. }
  34.  
  35. // IF METHOD
  36. // if (e.keyCode == 38) {
  37. // trace("up");
  38. // box_mc.y -= 10;
  39. // //box_mc.y = box_mc.y - 10;
  40. // } else if (e.keyCode == 40) {
  41. // box_mc.y += 10;
  42. // } else if (e.keyCode == 37) {
  43. // box_mc.x -= 10;
  44. // } else if (e.keyCode == 39) {
  45. // box_mc.x += 10;
  46. // }
  47.  
  48. }
  49.  
//Scrolling thumbnails within a bounding area, programmatic animation based on mouse position

View .swf file: scrolling_thumbs.swf | Download .fla file: scrolling_thumbs.fla (right click and "Save Link As")

  1. //Scrolling thumbnails within a bounding area, programmatic animation based on mouse position
  2. var xdistance:Number;
  3. var scrollspeed:Number = 8; //lower numbers equal faster speed
  4. panel_mc.addEventListener(MouseEvent.ROLL_OVER, onOver);
  5. function onOver(e:MouseEvent)
  6. {
  7. panel_mc.addEventListener(Event.ENTER_FRAME, onEnter);
  8. //establish enterframe loop and remove over event
  9. panel_mc.removeEventListener(MouseEvent.ROLL_OVER, onOver);
  10. function onEnter(e:Event)
  11. {
  12. //move panel_mc based on distance from center
  13. xdistance = mouseX - 250;
  14. panel_mc.x += Math.round(-xdistance/scrollspeed);
  15. //check if moving too far and set limits
  16. if (panel_mc.x >= 133) {
  17. panel_mc.x = 133;
  18. } else if (panel_mc.x <= -106) {
  19. panel_mc.x = -106;
  20. }
  21. //alternative to a rollout, check if outside of bounding area and if so remove enterframe loop
  22. if (mouseX<stroke_mc.x || mouseX>stroke_mc.width + stroke_mc.x || mouseY<stroke_mc.y || mouseY>stroke_mc.height + stroke_mc.y) {
  23. panel_mc.removeEventListener(Event.ENTER_FRAME, onEnter);
  24. panel_mc.addEventListener(MouseEvent.ROLL_OVER, onOver);
  25. }
  26. }
  27. }
  28. panel_mc.addEventListener(MouseEvent.CLICK, onClick);
  29. function onClick(e:MouseEvent) {
  30. trace(e.target.name);
  31. if (e.target.name == "b1") {
  32. trace ("Do whatever button 1 is supposed to do");
  33. }
  34. }
//Sound - Loading and Basic Controls

View .swf file: soundbasics.swf | Download .fla file: soundbasics.fla (right click and "Save Link As")

  1. //Scripting Sound
  2. //Loading an external mp3
  3. var mySound:Sound = new Sound();
  4. mySound.load(new URLRequest("fire.mp3"));
  5. mySound.play();
  6. ////The above can be shortened to 2 lines of code like this:
  7. var mySound2:Sound = new Sound(new URLRequest("whoosh.mp3"));
  8. mySound2.play();
  9. //Loading an internal sound
  10. var iSound:Sound = new Clang();
  11. iSound.play();
  12. ////Loading the full sound file or buffering a sound before playing
  13. var myMusic:Sound = new Sound();
  14. myMusic.load(new URLRequest("track1.mp3"));
  15. myMusic.addEventListener(Event.COMPLETE, onLoaded);
  16. function onLoaded(e:Event) {
  17. myMusic.play();
  18. }
  19. //Buffer a sound using the SoundLoaderContext class
  20. //Pass miliseconds to SoundLoaderContext parameters, so 100000 is 10 seconds of sound to load before playing
  21. var myContext:SoundLoaderContext = new SoundLoaderContext(10000);
  22. var myMusic2:Sound = new Sound();
  23. myMusic2.load(new URLRequest("track1.mp3"), myContext);
  24. myMusic2.play();
  25. //Controlling Sound
  26. var myMusic:Sound = new Sound();
  27. var myChannel:SoundChannel = new SoundChannel();
  28. var myTrans:SoundTransform = new SoundTransform();
  29. myMusic.load(new URLRequest("track1.mp3"));
  30. myChannel = myMusic.play();
  31. //the play method can take two parameters -- the offset (in miliseconds) and # of times to loop... so myMusic.play(1000, 3) would offset by 1 second and loop 3 times
  32. var pausePos:Number = 0; //keep track of position
  33. var musicPlaying:Boolean = true; //keep track of if playing or not
  34. stop_btn.addEventListener(MouseEvent.CLICK, onClick);
  35. play_btn.addEventListener(MouseEvent.CLICK, onClick);
  36. pause_btn.addEventListener(MouseEvent.CLICK, onClick);
  37. volDown_btn.addEventListener(MouseEvent.CLICK, onClick);
  38. volUp_btn.addEventListener(MouseEvent.CLICK, onClick);
  39. panRight_btn.addEventListener(MouseEvent.CLICK, onClick);
  40. panLeft_btn.addEventListener(MouseEvent.CLICK, onClick);
  41. function onClick(e:MouseEvent) {
  42. switch (e.target) {
  43. case stop_btn: //stop sound
  44. myChannel.stop();
  45. pausePos = 0;
  46. musicPlaying = false;
  47. break;
  48. case play_btn: //play sound only if not already playing
  49. if (!musicPlaying) {
  50. myChannel = myMusic.play(pausePos);
  51. musicPlaying = true;
  52. }
  53. break;
  54. case pause_btn: //pause sound by tracking position
  55. pausePos = myChannel.position;
  56. myChannel.stop();
  57. musicPlaying = false;
  58. break;
  59. case volDown_btn: //volume
  60. myTrans.volume -= .1;
  61. if (myTrans.volume < 0) {
  62. myTrans.volume = 0;
  63. }
  64. myChannel.soundTransform = myTrans;
  65. break;
  66. case volUp_btn:
  67. myTrans.volume += .1;
  68. myChannel.soundTransform = myTrans;
  69. break;
  70. case panRight_btn: //panning
  71. myTrans.pan = 1;
  72. myChannel.soundTransform = myTrans;
  73. break;
  74. case panLeft_btn:
  75. myTrans.pan = - 1;
  76. myChannel.soundTransform = myTrans;
  77. break;
  78. }
  79. }
//Sound - Advanced Controls, Sliders, Multi-Track, Keeping Track of Position/Time, Visualization

View .swf file: soundcontrols.swf | Download .fla file: soundcontrols.fla (right click and "Save Link As")

  1. //Sound - Advanced Controls, Sliders, Multi-Track, Keeping Track of Position/Time, Visualization
  2. var mySound:Sound = new Sound(); //create Sound object and assign in the variable name mySound
  3. var myChannel:SoundChannel = new SoundChannel(); //create SoundChannel, needed for controlling sound
  4. var mySoundTransform:SoundTransform = new SoundTransform(); //create SoundTransform needed for volume and panning
  5. var myFile:URLRequest = new URLRequest("track1.mp3"); //myFile is variable for the URLRequest
  6. mySound.load(myFile); //loads the file/request into the sound object
  7. var myPosition:Number = 0; //variable to track position of sound
  8. var soundPlaying:Boolean = false; //variable to track if sound is playing or not
  9. var skipSpeed:Number = 500; //variable for ff and rewind speed
  10. //Add event listeners to all button
  11. stop_btn.addEventListener(MouseEvent.CLICK, onClick);
  12. play_btn.addEventListener(MouseEvent.CLICK, onClick);
  13. pause_btn.addEventListener(MouseEvent.CLICK, onClick);
  14. track1_btn.addEventListener(MouseEvent.CLICK, onClick);
  15. track2_btn.addEventListener(MouseEvent.CLICK, onClick);
  16. //For rewind and ff use MOUSE_DOWN and MOUSE_UP so that you can hold the buttons down for continous effect
  17. rewind_btn.addEventListener(MouseEvent.MOUSE_DOWN, onSkipDown);
  18. ff_btn.addEventListener(MouseEvent.MOUSE_DOWN, onSkipDown);
  19. rewind_btn.addEventListener(MouseEvent.MOUSE_UP, onSkipUp);
  20. ff_btn.addEventListener(MouseEvent.MOUSE_UP, onSkipUp);
  21. function onClick(e:MouseEvent) {
  22. //With the switch conditional and the event target(e.target) we can use one oClick function for each of these buttons
  23. switch (e.target) {
  24. case play_btn: //if the target is the play_btn do this
  25. if (!soundPlaying) { //check if the sound is playing or not and if not do this
  26. myChannel = mySound.play(myPosition); //play wit offset of myPosition var
  27. myChannel.soundTransform = mySoundTransform; //apply any sound transformations too
  28. soundPlaying = true; // now its true that the sound is playing
  29. }
  30. break; // use the break statement to end each case
  31. case stop_btn:
  32. myChannel.stop(); //stop the sound in the sound channel
  33. soundPlaying = false;
  34. myPosition = 0; //reset the position var to 0 (rewind it)
  35. break;
  36. case pause_btn:
  37. myPosition = myChannel.position; //reset position var to current channel position to keep track of it
  38. myChannel.stop();
  39. soundPlaying = false
  40. break;
  41. case track1_btn: //change to track 1 -- stop the sound, say the sound is going to be new, and load/play it
  42. myChannel.stop();
  43. mySound = new Sound();
  44. myFile = new URLRequest("track1.mp3");
  45. mySound.load(myFile);
  46. myPosition = 0;
  47. myChannel = mySound.play(myPosition);
  48. myChannel.soundTransform = mySoundTransform;
  49. soundPlaying = true;
  50. break;
  51. case track2_btn: //change to track 2
  52. myChannel.stop();
  53. mySound = new Sound();
  54. myFile = new URLRequest("track2.mp3");
  55. mySound.load(myFile);
  56. myPosition = 0;
  57. myChannel = mySound.play(myPosition);
  58. myChannel.soundTransform = mySoundTransform;
  59. soundPlaying = true;
  60. break;
  61. }
  62. }
  63. //Rewind and FF functions
  64. function onSkipDown(e:MouseEvent) {
  65. switch (e.target) {
  66. case rewind_btn: //use enterframe event to continously rewind while down
  67. rewind_btn.addEventListener(Event.ENTER_FRAME, onRewind);
  68. break;
  69. case ff_btn: //use enterframe to continuously ff while down
  70. ff_btn.addEventListener(Event.ENTER_FRAME, onFF);
  71. break;
  72. }
  73. }
  74. function onSkipUp(e:MouseEvent) {
  75. skipSpeed = 500; //reset speed var
  76. switch (e.target) {
  77. case rewind_btn: //remove continous enterframe on up
  78. rewind_btn.removeEventListener(Event.ENTER_FRAME, onRewind);
  79. break;
  80. case ff_btn: //remove continous enterframe on up
  81. ff_btn.removeEventListener(Event.ENTER_FRAME, onFF);
  82. break;
  83. }
  84. }
  85. function onRewind(evt:Event) { //enterframe function to continously rewind
  86. myPosition = myChannel.position - skipSpeed; //subtract speed from current position
  87. skipSpeed +=100; //increase speed so rewind goes faster the longer you hold the buton down
  88. myChannel.stop(); //stop the sound
  89. myChannel = mySound.play(myPosition); //and replay from new position
  90. myChannel.soundTransform = mySoundTransform; //maintaining all transformations on the sound
  91. soundPlaying = true
  92. }
  93. function onFF(evt:Event) { //enterframe function to continously ff, similar to above for rewind
  94. myPosition = myChannel.position + skipSpeed;
  95. skipSpeed +=100;
  96. myChannel.stop();
  97. myChannel = mySound.play(myPosition);
  98. myChannel.soundTransform = mySoundTransform;
  99. soundPlaying = true
  100. }
  101. //VOLUME CONTROL - SLIDER BAR
  102. //Note the bar is 100 pixels in height which will allow for an easy conversion of 0 to 100% sound volume
  103. var constrain:Rectangle = new Rectangle(0, 0, 0, 100); //used to constrain the dragging of the slider
  104. var mySetting:int = 100 - bar_mc.vslide_mc.y; //The mySetting var will be used to determine volume setting, its based on y position of slider
  105. mySoundTransform.volume = mySetting/100; //divide transform by 100 sound that is within the range of 0 to 1 instead of 0 to 100
  106. bar_mc.vslide_mc.buttonMode = true; //gives you the hand cursor when over vslide_mc clip/button
  107. bar_mc.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
  108. function onDown(e:MouseEvent) {
  109. bar_mc.vslide_mc.startDrag(true ,constrain);//drag on down, set to the constraint so you can't drag outside of the bar
  110. }
  111. //bar_mc.addEventListener(MouseEvent.MOUSE_UP,onUp);
  112. stage.addEventListener(MouseEvent.MOUSE_UP,onUp); //call also outside of bar_mc, otherwise you'll keep dragging after rollout
  113. function onUp(e:MouseEvent) {
  114. bar_mc.vslide_mc.stopDrag(); //stop dragging the slider
  115. mySetting = 100 - bar_mc.vslide_mc.y; //reset the var based on slider y position
  116. trace(mySetting)
  117. mySoundTransform.volume = mySetting/100; //adjust sound volume based on new setting
  118. myChannel.soundTransform = mySoundTransform;
  119. }
  120. //PANNING CONROL SLIDER BAR
  121. //Panning works similar to volume slider, but with a wider bar of 200 pixels
  122. var myPanSetting:int = 100 - panbar_mc.vslide_mc.y;
  123. mySoundTransform.pan = myPanSetting/100;
  124. var constrain2:Rectangle = new Rectangle(0, 0, 0, 200);
  125. panbar_mc.vslide_mc.buttonMode = true;
  126. panbar_mc.addEventListener(MouseEvent.MOUSE_DOWN, onPanDown);
  127. function onPanDown(e:MouseEvent) {
  128. panbar_mc.vslide_mc.startDrag(true ,constrain2);
  129. }
  130. panbar_mc.addEventListener(MouseEvent.MOUSE_UP,onPanUp);
  131. stage.addEventListener(MouseEvent.MOUSE_UP,onPanUp);
  132. function onPanUp(e:MouseEvent) {
  133. panbar_mc.vslide_mc.stopDrag();
  134. myPanSetting = 100 - panbar_mc.vslide_mc.y;
  135. trace(myPanSetting)
  136. mySoundTransform.pan = myPanSetting/100;
  137. myChannel.soundTransform = mySoundTransform;
  138. }
  139. //KEEP TIME - Track current time and length of sound into text field
  140. stage.addEventListener(Event.ENTER_FRAME, keepTime); //keep time updated every frame
  141. function keepTime(e:Event) {
  142. // position_txt.text = String(int(myChannel.position/1000)); //this would work but is in total seconds rather than 0:00 format
  143. //variables for minutes, tens of seconds, and seconds so you can translate to 0:00 format from miliseconds
  144. //first calculate current position
  145. var minutes:Number = Math.floor(myChannel.position/60000); //minutes by dividing position by 60 seconds
  146. var seconds10:Number = Math.floor(((myChannel.position/1000) % 60)/10); //to get tens of seconds value use modulo (%) for remainder
  147. //modulo (%) returns remainder after division... so 10 % 6 would return 4 for example, whereas 10 % 5 returns 0 (no remainder)
  148. var seconds:Number = Math.floor(((myChannel.position/1000) % 60)%10); //gets seconds from 0 - 9
  149. //second calculate overall sound length
  150. var lminutes:Number = Math.floor(mySound.length/60000);
  151. var lseconds10:Number = Math.floor(((mySound.length/1000) % 60)/10);
  152. var lseconds:Number = Math.floor(((mySound.length/1000) % 60)%10);
  153. //third put all these variables into the text string for current position/song length
  154. position_txt.text = String(minutes) + ":" + String(seconds10) +""+ String(seconds) + " | " + String(lminutes) + ":" + String(lseconds10) +""+ String(lseconds)
  155. //keeping track of time has the added benefit of showing load progress as the sound length will continue to increase until sound fully loaded
  156. //SOUND VISUALIZATION -- also running on the keepTime EnterFrame event
  157. //rightPeak and leftPeak properties of the Sound Channel are easy ways to get amplitude info
  158. //Here the peak data manipulates the mask named peakbar_mc to reveal bar
  159. lpeakmeter_mc.peakbar_mc.height = myChannel.leftPeak * 200; //multiply by 200 to translate 0 to 1 into 0 to 200
  160. rpeakmeter_mc.peakbar_mc.height = myChannel.rightPeak * 200;
  161. //Compute Spectrum -- right click on computeSpectrum method to see flash help info upon which this is based
  162. var bytes:ByteArray = new ByteArray();
  163. //const PLOT_HEIGHT:int = 200;
  164. const PLOT_HEIGHT:int = 398;
  165. const CHANNEL_LENGTH:int = 256;
  166. //SoundMixer.computeSpectrum(bytes, false, 0);
  167. SoundMixer.computeSpectrum(bytes,true,0); //compute the spectrum and put in byte array
  168. var g:Graphics = this.graphics; // will make graphics based on spectrum
  169. g.clear(); //clear any current graphics
  170. //left channel graphics
  171. g.lineStyle(0, 0x000000, .5); //dictates line thickness, color, alpha)
  172. g.beginFill(0x000000, .3); //fill color, alpha
  173. g.moveTo(0, PLOT_HEIGHT); //set initial position of line
  174. var n:Number = 0;
  175. for (var i:int = 0; i < CHANNEL_LENGTH; i++) {
  176. n = (bytes.readFloat() * PLOT_HEIGHT);
  177. g.lineTo(i * 2.15, PLOT_HEIGHT - n); //draw line for all data in computeSpectrum byte array left channel (2.15 is the factor that will allow the graphics to extend all the way accross the stage (256 * 2.15 = 550, our stage with)
  178. }
  179. g.lineTo(CHANNEL_LENGTH * 2.15, PLOT_HEIGHT);
  180. g.endFill();
  181. //right channel graphics
  182. g.lineStyle(0, 0xFFFFFF, .5);
  183. g.beginFill(0xFFFFFF, 0.3);
  184. g.moveTo(CHANNEL_LENGTH * 2.15, PLOT_HEIGHT);
  185. for (i = CHANNEL_LENGTH; i > 0; i--) {
  186. n = (bytes.readFloat() * PLOT_HEIGHT);
  187. g.lineTo(i * 2.15, PLOT_HEIGHT - n);
  188. }
  189. g.lineTo(0, PLOT_HEIGHT);
  190. g.endFill();
  191. }
//Distance based collision detection

View .swf file: distance-based-collision-detection..swf | Download .fla file: distance-based-collision-detection.fla (right click and "Save Link As")

  1. //distance based collision detection
  2. mc1.startDrag(true);
  3. addEventListener(Event.ENTER_FRAME, onEnterFrame);
  4. function onEnterFrame(e:Event) {
  5. //determine the distance with the Pythagorean Theorem
  6. var dx:Number = mc2.x - mc1.x;
  7. var dy:Number = mc2.y - mc1.y;
  8. var distance:Number = Math.sqrt(dx * dx + dy * dy);
  9. //put distance into dynamic text field
  10. thedistance.text = Math.ceil(distance);
  11. //use distance to determine collision - I added 2 to accomodate the stroke
  12. if (distance < 62) {
  13. mc2.play();
  14. }
  15. //or use the movieclip widths rather than a number
  16. if (distance < mc1.width/2 + mc2.width/2) {
  17. thedistance.text = "HIT " + Math.ceil(distance);
  18. }
  19. }
//The Display List - Adding, Removing, and Reparenting Display Objects

View .swf file: DisplayList-Reparenting.swf | Download .fla file: DisplayList-Reparenting.fla (right click and "Save Link As")

  1. //The Display List, Adding, Removing, and Reparenting Display Objects
  2. //By Karl Cleveland - 2009
  3. //Calling the addChild() method a second time can move the display object to a different parent
  4. //Doing so also deletes the object from the orignal/previous parent without the need to remove it using removeChild first
  5. //Thus, you can easily move clips/content from one clip to another
  6. //To add object from library, it must be exported for Actionscript.
  7. var myPhoto = new Pic(); //Pic is the Class name of the movieclip in the library that was exported for AS
  8. //move the photo away from the top left 0, 0 corner, so it centers in parent containers once added
  9. myPhoto.x = 10;
  10. myPhoto.y = 10;
  11. //use addChild to add the Display list, in this case into the movieclip called "parent_mc"
  12. parent1_mc.addChild(myPhoto);
  13. //Toggle the parent of myPhoto
  14. move_btn.addEventListener(MouseEvent.CLICK, onClick);
  15. function onClick(e:MouseEvent) {
  16. //numChildren is a read-only property, returning the value of the number of display objects in the display object container
  17. //if > 1 checks if parent1_mc has more than just the background shape/graphic in it, but the photo too
  18. if (parent1_mc.numChildren > 1) {
  19. //if so, reparent the photo to parent2_mc
  20. parent2_mc.addChild(myPhoto);
  21. } else {
  22. parent1_mc.addChild(myPhoto);
  23. }
  24. }
  25. //removeChild can be used to remove the Photo... but doesn't delete it from memory
  26. myPhoto.addEventListener(MouseEvent.CLICK, onMyPhotoClick);
  27. function onMyPhotoClick(e:MouseEvent) {
  28. myPhoto.parent.removeChild(myPhoto);
  29. //myPhoto = null; //This would delete from memory, uncomment to test
  30. }
  31. //To cycle through and remove all objects in the display list, use the while loop
  32. //Hit the Space Bar to test/activate
  33. stage.addEventListener(KeyboardEvent.KEY_DOWN, onSpace);
  34. function onSpace(e:KeyboardEvent) {
  35. if (e.keyCode == Keyboard.SPACE) {
  36. //this removes all children from the root/main timeline dispaly list
  37. //but doesn't remove the listeners or delete the objects from memory -- which would be required for true/full removal
  38. while (numChildren > 0) {
  39. trace (numChildren);
  40. removeChildAt(0);
  41. }
  42. //For Resource Management/Garbage Collection you can aslo remove all object referenced and listeners like so
  43. move_btn.removeEventListener(MouseEvent.CLICK, onClick);
  44. myPhoto.removeEventListener(MouseEvent.CLICK, onMyPhotoClick);
  45. stage.removeEventListener(KeyboardEvent.KEY_DOWN, onSpace);
  46. myPhoto = null;
  47. parent1_mc = null;
  48. parent2_mc = null;
  49. move_btn = null;
  50. trace (numChildren + " - Everything removed");
  51. }
  52. }
//Timeline Scroller

View .swf file: Timeline_Scroller.swf | Download .fla file: Timeline_Scroller.fla (right click and "Save Link As")

  1. //This demo explores scrolling the timeline of a movieclip (called pics_mc) using buttons and a custom scrollbar. The coding of the buttons is below. The coding for the scrollbar at the bottom below.
  2. //By Karl Cleveland - 2009
  3. var currentf:int; //current frame var
  4. //The reposition function works for the jump buttons on the bottom; it progessively moves the timeline from its current frame to the target frame as passed to the function when it is called by the buttons.
  5. function reposition(targetframe) {
  6. //loop on enterFrame at the fps
  7. pics_mc.addEventListener(Event.ENTER_FRAME, onLoop);
  8. function onLoop(e:Event) {
  9. //what frame are we on?
  10. currentf = pics_mc.currentFrame;
  11. //how far do we have to go?
  12. var differencef = targetframe - currentf; //difference between current and target frames
  13. //how fast do we want to get there? How about 28% of the way at a time. The higher the number, the faster the speed.
  14. var speed =.28;
  15. //if there is no difference between our currentframe and the target, then let's remove the enterframe loop.
  16. if (differencef == 0) {
  17. trace("done");
  18. gotoAndStop(targetframe);
  19. pics_mc.removeEventListener(Event.ENTER_FRAME, onLoop);
  20. // otherwise move foward or back using our speed
  21. } else if (differencef > 0) {
  22. moveamount = Math.ceil(differencef*speed);
  23. moveto = currentf + moveamount;
  24. pics_mc.gotoAndStop(moveto);
  25. } else if (differencef < 0) {
  26. moveamount = Math.floor(differencef*speed);
  27. moveto = currentf + moveamount;
  28. pics_mc.gotoAndStop(moveto);
  29. }
  30. //we need to update the scrollbar to correspond to our new position, let's call the custom function
  31. updateScrollBar();
  32. //trace(currentf);
  33. }
  34. }
  35. //This function repositions the scrollbar
  36. function updateScrollBar() {
  37. //The factor is the length of the movieclip timeline (100 frames) divided by (the height of the scrollbar minus scroll button height).
  38. //240 - 30 = 210 --- 100/210 = .4762
  39. var factor:Number = pics_mc.totalFrames /(scrollbar_mc.height - scrollbar_mc.scroller_mc.height - 2);
  40. //var factor = .4762;
  41. currentf = pics_mc.currentFrame;
  42. scrollbar_mc.scroller_mc.y = Math.round(currentf/factor - 1);
  43. }
  44. //These buttton instances call the reposition function, with the target frame indicated in the parenthesis
  45. b1.addEventListener(MouseEvent.CLICK, onClick);
  46. b2.addEventListener(MouseEvent.CLICK, onClick);
  47. b3.addEventListener(MouseEvent.CLICK, onClick);
  48. b4.addEventListener(MouseEvent.CLICK, onClick);
  49. b5.addEventListener(MouseEvent.CLICK, onClick);
  50. b6.addEventListener(MouseEvent.CLICK, onClick);
  51. b7.addEventListener(MouseEvent.CLICK, onClick);
  52. b8.addEventListener(MouseEvent.CLICK, onClick);
  53. b9.addEventListener(MouseEvent.CLICK, onClick);
  54. b10.addEventListener(MouseEvent.CLICK, onClick);
  55. function onClick(e:MouseEvent) {
  56. switch (e.target) {
  57. case b1:
  58. reposition(1);
  59. break;
  60. case b2:
  61. reposition(12);
  62. break;
  63. case b3:
  64. reposition(23);
  65. break;
  66. case b4:
  67. reposition(34);
  68. break;
  69. case b5:
  70. reposition(45);
  71. break;
  72. case b6:
  73. reposition(56);
  74. break;
  75. case b7:
  76. reposition(67);
  77. break;
  78. case b8:
  79. reposition(78);
  80. break;
  81. case b9:
  82. reposition(89);
  83. break;
  84. case b10:
  85. reposition(100);
  86. break;
  87. }
  88. }
  89. var rate:Number;
  90. //The left and right buttons scroll the timeline with the speed increasing at a rate of 0.10
  91. rarrow_btn.addEventListener(MouseEvent.MOUSE_DOWN, onRArrowDown);
  92. function onRArrowDown(e:MouseEvent) {
  93. rate = 1;
  94. pics_mc.addEventListener(Event.ENTER_FRAME, onRLoop);
  95. }
  96. function onRLoop(e:Event) {
  97. //if we only want a frame at a time, we could use nextFrame
  98. //pics_mc.nextFrame();
  99. pics_mc.gotoAndStop(Math.floor(pics_mc.currentFrame + rate));
  100. rate += 0.1;
  101. updateScrollBar();
  102. }
  103. //Delete the scrolling on enterframe function on mouse up
  104. rarrow_btn.addEventListener(MouseEvent.MOUSE_UP, onRArrowUp);
  105. function onRArrowUp(e:MouseEvent) {
  106. pics_mc.removeEventListener(Event.ENTER_FRAME, onRLoop);
  107. }
  108. larrow_btn.addEventListener(MouseEvent.MOUSE_DOWN, onLArrowDown);
  109. function onLArrowDown(e:MouseEvent) {
  110. rate = 1;
  111. pics_mc.addEventListener(Event.ENTER_FRAME, onLLoop);
  112. }
  113. function onLLoop(e:Event) {
  114. //pics_mc.prevFrame();
  115. pics_mc.gotoAndStop(Math.floor(pics_mc.currentFrame - rate));
  116. //You can't go a frame less than zero, so if it trys... let's just go to frame 1
  117. if (Math.floor(pics_mc.currentFrame - rate) < 1) {
  118. pics_mc.gotoAndStop(1);
  119. }
  120. rate += 0.1;
  121. updateScrollBar();
  122. }
  123. larrow_btn.addEventListener(MouseEvent.MOUSE_UP, onLArrowUp);
  124. function onLArrowUp(e:MouseEvent) {
  125. pics_mc.removeEventListener(Event.ENTER_FRAME, onLLoop);
  126. }
  127. //larrow_btn.onReleaseOutside= function() {
  128. // delete pics_mc.onEnterFrame;
  129. //}
  130. //Scrollbar code
  131. var dragging:Boolean = false;
  132. scrollbar_mc.scroller_mc.scroller_btn.addEventListener(MouseEvent.MOUSE_DOWN, onScrollBtnDown);
  133. function onScrollBtnDown(e:MouseEvent) {
  134. //when you press the scroll button start draging it, constrained to the vertical length of the scrolling bar/area
  135. var myContrainRect:Rectangle = new Rectangle(0,0,0,210);
  136. scrollbar_mc.scroller_mc.startDrag(false, myContrainRect);
  137. dragging = true;
  138. //The mover function makes the timeline move to the appropriate frame
  139. stage.addEventListener(MouseEvent.MOUSE_MOVE, onMove);
  140. }
  141. //Delete the scrolling on up... (or on release outside or up on stage code also below)
  142. scrollbar_mc.scroller_mc.scroller_btn.addEventListener(MouseEvent.MOUSE_UP, onScrollBtnUp);
  143. function onScrollBtnUp(e:MouseEvent) {
  144. trace(scrollbar_mc.scroller_mc.y);
  145. scrollbar_mc.scroller_mc.stopDrag();
  146. stage.removeEventListener(MouseEvent.MOUSE_MOVE, onMove)
  147. }
  148. function onMove(e:MouseEvent) {
  149. //The factor is the length of the movieclip timeline (100 frames) divided by the height of the scrollbar (210). Take the y position of the scroll bar button and use it to determine the appropriate frame to goto in the movieclip.
  150. var factor:Number = pics_mc.totalFrames /(scrollbar_mc.height - scrollbar_mc.scroller_mc.height - 2);
  151. //factor = .4762;
  152. mytarget = Math.ceil(scrollbar_mc.scroller_mc.y*factor);
  153. pics_mc.gotoAndStop(mytarget);
  154. e.updateAfterEvent();
  155. //trace(mytarget);
  156. }
  157. //code to remove scrolling if you've moved off the buttons (to the stage) and then release/up the mouse
  158. stage.addEventListener(MouseEvent.MOUSE_UP, onScrollBtnUpOutside);
  159. function onScrollBtnUpOutside(e:MouseEvent) {
  160. if (dragging) {
  161. trace(scrollbar_mc.scroller_mc.y);
  162. scrollbar_mc.scroller_mc.stopDrag();
  163. stage.removeEventListener(MouseEvent.MOUSE_MOVE, onMove)
  164. }
  165. pics_mc.removeEventListener(Event.ENTER_FRAME, onLLoop);
  166. pics_mc.removeEventListener(Event.ENTER_FRAME, onRLoop);
  167. }