TimelineMax.as 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. /**
  2. * VERSION: 1.381
  3. * DATE: 2010-05-17
  4. * AS3 (AS2 version is also available)
  5. * UPDATES AND DOCUMENTATION AT: http://www.greensock.com/timelinemax/
  6. **/
  7. package com.greensock {
  8. import com.greensock.core.*;
  9. import com.greensock.events.TweenEvent;
  10. import flash.events.*;
  11. import flash.utils.*;
  12. /**
  13. * TimelineMax extends TimelineLite, offering exactly the same functionality plus useful
  14. * (but non-essential) features like AS3 event dispatching, repeat, repeatDelay, yoyo,
  15. * currentLabel, addCallback(), removeCallback(), tweenTo(), tweenFromTo(), getLabelAfter(), getLabelBefore(),
  16. * and getActive() (and probably more in the future). It is the ultimate sequencing tool.
  17. * Think of a TimelineMax instance like a virtual MovieClip timeline or a container where
  18. * you place tweens (or other timelines) over the course of time. You can:
  19. *
  20. * <ul>
  21. * <li> build sequences easily by adding tweens with the append(), prepend(), insert(), appendMultiple(),
  22. * prependMultiple(), and insertMultiple() methods. Tweens can overlap as much as you want and you have
  23. * complete control over where they get placed on the timeline.</li>
  24. *
  25. * <li> add labels, play(), stop(), gotoAndPlay(), gotoAndStop(), restart(), tweenTo() and even reverse()! </li>
  26. *
  27. * <li> nest timelines within timelines as deeply as you want.</li>
  28. *
  29. * <li> set the progress of the timeline using its <code>currentProgress</code> property. For example, to skip to
  30. * the halfway point, set <code>myTimeline.currentProgress = 0.5</code>.</li>
  31. *
  32. * <li> tween the <code>currentTime</code>, <code>totalTime</code>, <code>currentProgress</code>, or <code>totalProgress</code>
  33. * property to fastforward/rewind the timeline. You could
  34. * even attach a slider to one of these properties to give the user the ability to drag
  35. * forwards/backwards through the whole timeline.</li>
  36. *
  37. * <li> add onStart, onUpdate, onComplete, onReverseComplete, and/or onRepeat callbacks using the
  38. * constructor's <code>vars</code> object.</li>
  39. *
  40. * <li> speed up or slow down the entire timeline with its <code>timeScale</code> property. You can even tween
  41. * this property to gradually speed up or slow down the timeline.</li>
  42. *
  43. * <li> use the insertMultiple(), appendMultiple(), or prependMultiple() methods to create
  44. * complex sequences including various alignment modes and staggering capabilities.
  45. * Works great in conjunction with TweenMax.allTo() too. </li>
  46. *
  47. * <li> base the timing on frames instead of seconds if you prefer. Please note, however, that
  48. * the timeline's timing mode dictates its childrens' timing mode as well. </li>
  49. *
  50. * <li> kill the tweens of a particular object inside the timeline with killTweensOf() or get the tweens of an object
  51. * with getTweensOf() or get all the tweens/timelines in the timeline with getChildren()</li>
  52. *
  53. * <li> set the timeline to repeat any number of times or indefinitely. You can even set a delay
  54. * between each repeat cycle and/or cause the repeat cycles to yoyo, appearing to reverse
  55. * every other cycle. </li>
  56. *
  57. * <li> listen for START, UPDATE, REPEAT, REVERSE_COMPLETE, and COMPLETE events.</li>
  58. *
  59. * <li> get the active tweens in the timeline with getActive().</li>
  60. *
  61. * <li> add callbacks (function calls) anywhere in the timeline that call a function of your choosing when
  62. * the "virtual playhead" passes a particular spot.</li>
  63. *
  64. * <li> Get the <code>currentLabel</code> or find labels at various positions in the timeline
  65. * using getLabelAfter() and getLabelBefore()</li>
  66. * </ul>
  67. *
  68. * <b>EXAMPLE:</b><br /><br /><code>
  69. *
  70. * import com.greensock.~~;<br /><br />
  71. *
  72. * //create the timeline and add an onComplete call to myFunction when the timeline completes<br />
  73. * var myTimeline:TimelineMax = new TimelineMax({onComplete:myFunction});<br /><br />
  74. *
  75. * //add a tween<br />
  76. * myTimeline.append(new TweenLite(mc, 1, {x:200, y:100}));<br /><br />
  77. *
  78. * //add another tween at the end of the timeline (makes sequencing easy)<br />
  79. * myTimeline.append(new TweenLite(mc, 0.5, {alpha:0}));<br /><br />
  80. *
  81. * //repeat the entire timeline twice<br />
  82. * myTimeline.repeat = 2;<br /><br />
  83. *
  84. * //delay the repeat by 0.5 seconds each time.<br />
  85. * myTimeline.repeatDelay = 0.5;<br /><br />
  86. *
  87. * //pause the timeline (stop() works too)<br />
  88. * myTimeline.pause();<br /><br />
  89. *
  90. * //reverse it anytime...<br />
  91. * myTimeline.reverse();<br /><br />
  92. *
  93. * //Add a "spin" label 3-seconds into the timeline.<br />
  94. * myTimeline.addLabel("spin", 3);<br /><br />
  95. *
  96. * //insert a rotation tween at the "spin" label (you could also define the insert point as the time instead of a label)<br />
  97. * myTimeline.insert(new TweenLite(mc, 2, {rotation:"360"}), "spin"); <br /><br />
  98. *
  99. * //go to the "spin" label and play the timeline from there...<br />
  100. * myTimeline.gotoAndPlay("spin");<br /><br />
  101. *
  102. * //call myCallbackwhen the "virtual playhead" travels past the 1.5-second point.
  103. * myTimeline.addCallback(myCallback, 1.5);
  104. *
  105. * //add a tween to the beginning of the timeline, pushing all the other existing tweens back in time<br />
  106. * myTimeline.prepend(new TweenMax(mc, 1, {tint:0xFF0000}));<br /><br />
  107. *
  108. * //nest another TimelineMax inside your timeline...<br />
  109. * var nestedTimeline:TimelineMax = new TimelineMax();<br />
  110. * nestedTimeline.append(new TweenLite(mc2, 1, {x:200}));<br />
  111. * myTimeline.append(nestedTimeline);<br /><br /></code>
  112. *
  113. *
  114. * <code>insertMultiple()</code> and <code>appendMultiple()</code> provide some very powerful sequencing tools as well,
  115. * allowing you to add an Array of tweens/timelines and optionally align them with <code>SEQUENCE</code> or <code>START</code>
  116. * modes, and even stagger them if you want. For example, to insert 3 tweens into the timeline, aligning their start times but
  117. * staggering them by 0.2 seconds, <br /><br /><code>
  118. *
  119. * myTimeline.insertMultiple([new TweenLite(mc, 1, {y:"100"}),
  120. * new TweenLite(mc2, 1, {x:120}),
  121. * new TweenLite(mc3, 1, {alpha:0.5})],
  122. * 0,
  123. * TweenAlign.START,
  124. * 0.2);</code><br /><br />
  125. *
  126. * You can use the constructor's <code>vars</code> object to do all the setup too, like:<br /><br /><code>
  127. *
  128. * var myTimeline:TimelineMax = new TimelineMax({tweens:[new TweenLite(mc1, 1, {y:"100"}), TweenMax.to(mc2, 1, {tint:0xFF0000})], align:TweenAlign.SEQUENCE, onComplete:myFunction, repeat:2, repeatDelay:1});</code><br /><br />
  129. *
  130. * If that confuses you, don't worry. Just use the <code>append()</code>, <code>insert()</code>, and <code>prepend()</code> methods to build your
  131. * sequence. But power users will likely appreciate the quick, compact way they can set up sequences now. <br /><br />
  132. *
  133. *
  134. * <b>NOTES:</b>
  135. * <ul>
  136. * <li> TimelineMax automatically inits the OverwriteManager class to prevent unexpected overwriting behavior in sequences.
  137. * The default mode is <code>AUTO</code>, but you can set it to whatever you want with <code>OverwriteManager.init()</code>
  138. * (see <a href="http://www.greensock.com/overwritemanager/">http://www.greensock.com/overwritemanager/</a>)</li>
  139. * <li> TimelineMax adds about 4.9k to your SWF (not including OverwriteManager).</li>
  140. * </ul>
  141. *
  142. * <b>Copyright 2010, GreenSock. All rights reserved.</b> This work is subject to the terms in <a href="http://www.greensock.com/terms_of_use.html">http://www.greensock.com/terms_of_use.html</a> or for corporate Club GreenSock members, the software agreement that was issued with the corporate membership.
  143. *
  144. * @author Jack Doyle, jack@greensock.com
  145. **/
  146. public class TimelineMax extends TimelineLite implements IEventDispatcher {
  147. /** @private **/
  148. public static const version:Number = 1.381;
  149. /** @private **/
  150. protected var _repeat:int;
  151. /** @private **/
  152. protected var _repeatDelay:Number;
  153. /** @private **/
  154. protected var _cyclesComplete:uint;
  155. /** @private **/
  156. protected var _dispatcher:EventDispatcher;
  157. /** @private **/
  158. protected var _hasUpdateListener:Boolean;
  159. /**
  160. * Works in conjunction with the repeat property, determining the behavior of each cycle; when <code>yoyo</code> is true,
  161. * the timeline will go back and forth, appearing to reverse every other cycle (this has no affect on the <code>reversed</code> property though).
  162. * So if repeat is 2 and <code>yoyo</code> is false, it will look like: start - 1 - 2 - 3 - 1 - 2 - 3 - 1 - 2 - 3 - end.
  163. * But if repeat is 2 and <code>yoyo</code> is true, it will look like: start - 1 - 2 - 3 - 3 - 2 - 1 - 1 - 2 - 3 - end.
  164. **/
  165. public var yoyo:Boolean;
  166. /**
  167. * Constructor. <br /><br />
  168. *
  169. * <b>SPECIAL PROPERTIES</b><br />
  170. * The following special properties may be passed in via the constructor's vars parameter, like
  171. * <code>new TimelineMax({paused:true, onComplete:myFunction, repeat:2, yoyo:true})</code>
  172. *
  173. * <ul>
  174. * <li><b> delay : Number</b> Amount of delay in seconds (or frames for frames-based timelines) before the timeline should begin.</li>
  175. *
  176. * <li><b> useFrames : Boolean</b> If <code>useFrames</code> is set to true, the timeline's timing mode will be based on frames.
  177. * Otherwise, it will be based on seconds/time. NOTE: a TimelineLite's timing mode is
  178. * always determined by its parent timeline. </li>
  179. *
  180. * <li><b> paused : Boolean</b> Sets the initial paused state of the timeline (by default, timelines automatically begin playing immediately)</li>
  181. *
  182. * <li><b> reversed : Boolean</b> If true, the timeline will be reversed initially. This does NOT force it to the very end and start
  183. * playing backwards. It simply affects the orientation of the timeline, so if <code>reversed</code> is set to
  184. * true initially, it will appear not to play because it is already at the beginning. To cause it to
  185. * play backwards from the end, set reversed to true and then set the <code>currentProgress</code> property to 1 immediately
  186. * after creating the timeline.</li>
  187. *
  188. * <li><b> tweens : Array</b> To immediately insert several tweens into the timeline, use the <code>tweens</code> special property
  189. * to pass in an Array of TweenLite/TweenMax/TimelineLite/TimelineMax instances. You can use this in conjunction
  190. * with the <code>align</code> and <code>stagger</code> special properties to set up complex sequences with minimal code.
  191. * These values simply get passed to the <code>insertMultiple()</code> method.</li>
  192. *
  193. * <li><b> align : String</b> Only used in conjunction with the <code>tweens</code> special property when multiple tweens are
  194. * to be inserted immediately through the constructor. The value simply gets passed to the
  195. * <code>insertMultiple()</code> method. The default is <code>TweenAlign.NORMAL</code>. Options are:
  196. * <ul>
  197. * <li><b> TweenAlign.SEQUENCE:</b> aligns the tweens one-after-the-other in a sequence</li>
  198. * <li><b> TweenAlign.START:</b> aligns the start times of all of the tweens (ignores delays)</li>
  199. * <li><b> TweenAlign.NORMAL:</b> aligns the start times of all the tweens (honors delays)</li>
  200. * </ul>The <code>align</code> special property does <b>not</b> force all child tweens/timelines to maintain
  201. * relative positioning, so for example, if you use TweenAlign.SEQUENCE and then later change the duration
  202. * of one of the nested tweens, it does <b>not</b> force all subsequent timelines to change their position
  203. * on the timeline. The <code>align</code> special property only affects the alignment of the tweens that are
  204. * initially placed into the timeline through the <code>tweens</code> special property of the <code>vars</code> object.</li>
  205. *
  206. * <li><b> stagger : Number</b> Only used in conjunction with the <code>tweens</code> special property when multiple tweens are
  207. * to be inserted immediately. It staggers the tweens by a set amount of time (in seconds) (or
  208. * in frames if <code>useFrames</code> is true). For example, if the stagger value is 0.5 and the <code>align</code>
  209. * property is set to <code>TweenAlign.START</code>, the second tween will start 0.5 seconds after the first one
  210. * starts, then 0.5 seconds later the third one will start, etc. If the align property is
  211. * <code>TweenAlign.SEQUENCE</code>, there would be 0.5 seconds added between each tween. This value simply gets
  212. * passed to the <code>insertMultiple()</code> method. Default is 0.</li>
  213. *
  214. * <li><b> onStart : Function</b> A function that should be called when the timeline begins (the <code>currentProgress</code> won't necessarily
  215. * be zero when onStart is called. For example, if the timeline is created and then its <code>currentProgress</code>
  216. * property is immediately set to 0.5 or if its <code>currentTime</code> property is set to something other than zero,
  217. * onStart will still get fired because it is the first time the timeline is getting rendered.)</li>
  218. *
  219. * <li><b> onStartParams : Array</b> An Array of parameters to pass the onStart function.</li>
  220. *
  221. * <li><b> onUpdate : Function</b> A function that should be called every time the timeline's time/position is updated
  222. * (on every frame while the timeline is active)</li>
  223. *
  224. * <li><b> onUpdateParams : Array</b> An Array of parameters to pass the onUpdate function</li>
  225. *
  226. * <li><b> onComplete : Function</b> A function that should be called when the timeline has finished </li>
  227. *
  228. * <li><b> onCompleteParams : Array</b> An Array of parameters to pass the onComplete function</li>
  229. *
  230. * <li><b> onReverseComplete : Function</b> A function that should be called when the timeline has reached its starting point again after having been reversed </li>
  231. *
  232. * <li><b> onReverseCompleteParams : Array</b> An Array of parameters to pass the onReverseComplete functions</li>
  233. *
  234. * <li><b> onRepeat : Function</b> A function that should be called every time the timeline repeats </li>
  235. *
  236. * <li><b> onRepeatParams : Array</b> An Array of parameters to pass the onRepeat function</li>
  237. *
  238. * <li><b> autoRemoveChildren : Boolean</b> If autoRemoveChildren is set to true, as soon as child tweens/timelines complete,
  239. * they will automatically get killed/removed. This is normally undesireable because
  240. * it prevents going backwards in time (like if you want to reverse() or set the
  241. * <code>currentProgress</code> value to a lower value, etc.). It can, however, improve speed and memory
  242. * management. TweenLite's root timelines use <code>autoRemoveChildren:true</code>.</li>
  243. *
  244. * <li><b> repeat : int</b> Number of times that the timeline should repeat. To repeat indefinitely, use -1.</li>
  245. *
  246. * <li><b> repeatDelay : Number</b> Amount of time in seconds (or frames for frames-based timelines) between repeats.</li>
  247. *
  248. * <li><b> yoyo : Boolean</b> Works in conjunction with the repeat property, determining the behavior of each
  249. * cycle. When <code>yoyo</code> is true, the timeline will go back and forth, appearing to reverse
  250. * every other cycle (this has no affect on the <code>reversed</code> property though). So if repeat is
  251. * 2 and yoyo is false, it will look like: start - 1 - 2 - 3 - 1 - 2 - 3 - 1 - 2 - 3 - end. But
  252. * if repeat is 2 and yoyo is true, it will look like: start - 1 - 2 - 3 - 3 - 2 - 1 - 1 - 2 - 3 - end. </li>
  253. *
  254. * <li><b> onStartListener : Function</b> A function to which the TimelineMax instance should dispatch a TweenEvent when it begins.
  255. * This is the same as doing <code>myTimeline.addEventListener(TweenEvent.START, myFunction);</code></li>
  256. *
  257. * <li><b> onUpdateListener : Function</b> A function to which the TimelineMax instance should dispatch a TweenEvent every time it
  258. * updates values. This is the same as doing <code>myTimeline.addEventListener(TweenEvent.UPDATE, myFunction);</code></li>
  259. *
  260. * <li><b> onCompleteListener : Function</b> A function to which the TimelineMax instance should dispatch a TweenEvent when it completes.
  261. * This is the same as doing <code>myTimeline.addEventListener(TweenEvent.COMPLETE, myFunction);</code></li>
  262. * </ul>
  263. *
  264. * @param vars optionally pass in special properties like useFrames, onComplete, onCompleteParams, onUpdate, onUpdateParams, onStart, onStartParams, tweens, align, stagger, delay, autoRemoveChildren, onCompleteListener, onStartListener, onUpdateListener, repeat, repeatDelay, and/or yoyo.
  265. */
  266. public function TimelineMax(vars:Object=null) {
  267. super(vars);
  268. _repeat = (this.vars.repeat) ? Number(this.vars.repeat) : 0;
  269. _repeatDelay = (this.vars.repeatDelay) ? Number(this.vars.repeatDelay) : 0;
  270. _cyclesComplete = 0;
  271. this.yoyo = Boolean(this.vars.yoyo == true);
  272. this.cacheIsDirty = true;
  273. if (this.vars.onCompleteListener != null || this.vars.onUpdateListener != null || this.vars.onStartListener != null || this.vars.onRepeatListener != null || this.vars.onReverseCompleteListener != null) {
  274. initDispatcher();
  275. }
  276. }
  277. /**
  278. * If you want a function to be called at a particular time or label, use addCallback. When you add
  279. * a callback, it is technically considered a zero-duration tween, so if you getChildren() there will be
  280. * a tween returned for each callback. You can discern a callback from other tweens by the fact that
  281. * their target is a function and the duration is zero.
  282. *
  283. * @param function the function to be called
  284. * @param timeOrLabel the time in seconds (or frames for frames-based timelines) or label at which the callback should be inserted. For example, myTimeline.addCallback(myFunction, 3) would call myFunction() 3-seconds into the timeline, and myTimeline.addCallback(myFunction, "myLabel") would call it at the "myLabel" label.
  285. * @param params an Array of parameters to pass the callback
  286. * @return TweenLite instance
  287. */
  288. public function addCallback(callback:Function, timeOrLabel:*, params:Array=null):TweenLite {
  289. var cb:TweenLite = new TweenLite(callback, 0, {onComplete:callback, onCompleteParams:params, overwrite:0, immediateRender:false});
  290. insert(cb, timeOrLabel);
  291. return cb;
  292. }
  293. /**
  294. * Removes a callback from a particular time or label. If timeOrLabel is null, all callbacks of that
  295. * particular function are removed from the timeline.
  296. *
  297. * @param function callback function to be removed
  298. * @param timeOrLabel the time in seconds (or frames for frames-based timelines) or label from which the callback should be removed. For example, <code>myTimeline.removeCallback(myFunction, 3)</code> would remove the callback from 3-seconds into the timeline, and <code>myTimeline.removeCallback(myFunction, "myLabel")</code> would remove it from the "myLabel" label, and <code>myTimeline.removeCallback(myFunction, null)</code> would remove ALL callbacks of that function regardless of where they are on the timeline.
  299. * @return true if any callbacks were successfully found and removed. false otherwise.
  300. */
  301. public function removeCallback(callback:Function, timeOrLabel:*=null):Boolean {
  302. if (timeOrLabel == null) {
  303. return killTweensOf(callback, false);
  304. } else {
  305. if (typeof(timeOrLabel) == "string") {
  306. if (!(timeOrLabel in _labels)) {
  307. return false;
  308. }
  309. timeOrLabel = _labels[timeOrLabel];
  310. }
  311. var a:Array = getTweensOf(callback, false), success:Boolean;
  312. var i:int = a.length;
  313. while (--i > -1) {
  314. if (a[i].cachedStartTime == timeOrLabel) {
  315. remove(a[i] as TweenCore);
  316. success = true;
  317. }
  318. }
  319. return success;
  320. }
  321. }
  322. /**
  323. * Creates a linear tween that essentially scrubs the playhead to a particular time or label and then stops. For
  324. * example, to make the TimelineMax play to the "myLabel2" label, simply do: <br /><br /><code>
  325. *
  326. * myTimeline.tweenTo("myLabel2"); <br /><br /></code>
  327. *
  328. * If you want advanced control over the tween, like adding an onComplete or changing the ease or adding a delay,
  329. * just pass in a vars object with the appropriate properties. For example, to tween to the 5-second point on the
  330. * timeline and then call a function named <code>myFunction</code> and pass in a parameter that's references this
  331. * TimelineMax and use a Strong.easeOut ease, you'd do: <br /><br /><code>
  332. *
  333. * myTimeline.tweenTo(5, {onComplete:myFunction, onCompleteParams:[myTimeline], ease:Strong.easeOut});<br /><br /></code>
  334. *
  335. * Remember, this method simply creates a TweenLite instance that tweens the <code>currentTime</code> property of your timeline.
  336. * So you can store a reference to that tween if you want, and you can kill() it anytime. Also note that <code>tweenTo()</code>
  337. * does <b>NOT</b> affect the timeline's <code>reversed</code> property. So if your timeline is oriented normally
  338. * (not reversed) and you tween to a time/label that precedes the current time, it will appear to go backwards
  339. * but the <code>reversed</code> property will <b>not</b> change to <code>true</code>. Also note that <code>tweenTo()</code>
  340. * pauses the timeline immediately before tweening its <code>currentTime</code> property, and it stays paused after the tween completes.
  341. * If you need to resume playback, you could always use an onComplete to call the <code>resume()</code> method.<br /><br />
  342. *
  343. * If you plan to sequence multiple playhead tweens one-after-the-other, it is typically better to use
  344. * <code>tweenFromTo()</code> so that you can define the starting point and ending point, allowing the
  345. * duration to be accurately determined immediately.
  346. *
  347. * @see #tweenFromTo()
  348. * @param timeOrLabel The destination time in seconds (or frame if the timeline is frames-based) or label to which the timeline should play. For example, myTimeline.tweenTo(5) would play from wherever the timeline is currently to the 5-second point whereas myTimeline.tweenTo("myLabel") would play to wherever "myLabel" is on the timeline.
  349. * @param vars An optional vars object that will be passed to the TweenLite instance. This allows you to define an onComplete, ease, delay, or any other TweenLite special property. onInit is the only special property that is not available (tweenTo() sets it internally)
  350. * @return TweenLite instance that handles tweening the timeline to the desired time/label.
  351. */
  352. public function tweenTo(timeOrLabel:*, vars:Object=null):TweenLite {
  353. var varsCopy:Object = {ease:easeNone, overwrite:2, useFrames:this.useFrames, immediateRender:false};
  354. for (var p:String in vars) {
  355. varsCopy[p] = vars[p];
  356. }
  357. varsCopy.onInit = onInitTweenTo;
  358. varsCopy.onInitParams = [null, this, NaN];
  359. varsCopy.currentTime = parseTimeOrLabel(timeOrLabel);
  360. var tl:TweenLite = new TweenLite(this, (Math.abs(Number(varsCopy.currentTime) - this.cachedTime) / this.cachedTimeScale) || 0.001, varsCopy);
  361. tl.vars.onInitParams[0] = tl;
  362. return tl;
  363. }
  364. /**
  365. * Creates a linear tween that essentially scrubs the playhead from a particular time or label to another
  366. * time or label and then stops. If you plan to sequence multiple playhead tweens one-after-the-other,
  367. * <code>tweenFromTo()</code> is better to use than <code>tweenTo()</code> because it allows the duration
  368. * to be determined immediately, ensuring that subsequent tweens that are appended to a sequence are
  369. * positioned appropriately. For example, to make the TimelineMax play from the label "myLabel1" to the "myLabel2"
  370. * label, and then from "myLabel2" back to the beginning (a time of 0), simply do: <br /><br /><code>
  371. *
  372. * var playheadTweens:TimelineMax = new TimelineMax(); <br />
  373. * playheadTweens.append( myTimeline.tweenFromTo("myLabel1", "myLabel2") );<br />
  374. * playheadTweens.append( myTimeline.tweenFromTo("myLabel2", 0); <br /><br /></code>
  375. *
  376. * If you want advanced control over the tween, like adding an onComplete or changing the ease or adding a delay,
  377. * just pass in a vars object with the appropriate properties. For example, to tween from the start (0) to the
  378. * 5-second point on the timeline and then call a function named <code>myFunction</code> and pass in a parameter
  379. * that's references this TimelineMax and use a Strong.easeOut ease, you'd do: <br /><br /><code>
  380. *
  381. * myTimeline.tweenFromTo(0, 5, {onComplete:myFunction, onCompleteParams:[myTimeline], ease:Strong.easeOut});<br /><br /></code>
  382. *
  383. * Remember, this method simply creates a TweenLite instance that tweens the <code>currentTime</code> property of your timeline.
  384. * So you can store a reference to that tween if you want, and you can <code>kill()</code> it anytime. Also note that <code>tweenFromTo()</code>
  385. * does <b>NOT</b> affect the timeline's <code>reversed</code> property. So if your timeline is oriented normally
  386. * (not reversed) and you tween to a time/label that precedes the current time, it will appear to go backwards
  387. * but the <code>reversed</code> property will <b>not</b> change to <code>true</code>. Also note that <code>tweenFromTo()</code>
  388. * pauses the timeline immediately before tweening its <code>currentTime</code> property, and it stays paused after the tween completes.
  389. * If you need to resume playback, you could always use an onComplete to call the <code>resume()</code> method.
  390. *
  391. * @see #tweenTo()
  392. * @param fromTimeOrLabel The beginning time in seconds (or frame if the timeline is frames-based) or label from which the timeline should play. For example, <code>myTimeline.tweenTo(0, 5)</code> would play from 0 (the beginning) to the 5-second point whereas <code>myTimeline.tweenFromTo("myLabel1", "myLabel2")</code> would play from "myLabel1" to "myLabel2".
  393. * @param toTimeOrLabel The destination time in seconds (or frame if the timeline is frames-based) or label to which the timeline should play. For example, <code>myTimeline.tweenTo(0, 5)</code> would play from 0 (the beginning) to the 5-second point whereas <code>myTimeline.tweenFromTo("myLabel1", "myLabel2")</code> would play from "myLabel1" to "myLabel2".
  394. * @param vars An optional vars object that will be passed to the TweenLite instance. This allows you to define an onComplete, ease, delay, or any other TweenLite special property. onInit is the only special property that is not available (<code>tweenFromTo()</code> sets it internally)
  395. * @return TweenLite instance that handles tweening the timeline between the desired times/labels.
  396. */
  397. public function tweenFromTo(fromTimeOrLabel:*, toTimeOrLabel:*, vars:Object=null):TweenLite {
  398. var tl:TweenLite = tweenTo(toTimeOrLabel, vars);
  399. tl.vars.onInitParams[2] = parseTimeOrLabel(fromTimeOrLabel);
  400. tl.duration = Math.abs(Number(tl.vars.currentTime) - tl.vars.onInitParams[2]) / this.cachedTimeScale;
  401. return tl;
  402. }
  403. /** @private **/
  404. private static function onInitTweenTo(tween:TweenLite, timeline:TimelineMax, fromTime:Number):void {
  405. timeline.paused = true;
  406. if (!isNaN(fromTime)) {
  407. timeline.currentTime = fromTime;
  408. }
  409. if (tween.vars.currentTime != timeline.currentTime) { //don't make the duration zero - if it's supposed to be zero, don't worry because it's already initting the tween and will complete immediately, effectively making the duration zero anyway. If we make duration zero, the tween won't run at all.
  410. tween.duration = Math.abs(Number(tween.vars.currentTime) - timeline.currentTime) / timeline.cachedTimeScale;
  411. }
  412. }
  413. /** @private **/
  414. private static function easeNone(t:Number, b:Number, c:Number, d:Number):Number {
  415. return t / d;
  416. }
  417. /** @private **/
  418. override public function renderTime(time:Number, suppressEvents:Boolean=false, force:Boolean=false):void {
  419. if (this.gc) {
  420. this.setEnabled(true, false);
  421. } else if (!this.active && !this.cachedPaused) {
  422. this.active = true; //so that if the user renders a tween (as opposed to the timeline rendering it), the timeline is forced to re-render and align it with the proper time/frame on the next rendering cycle. Maybe the tween already finished but the user manually re-renders it as halfway done.
  423. }
  424. var totalDur:Number = (this.cacheIsDirty) ? this.totalDuration : this.cachedTotalDuration, prevTime:Number = this.cachedTime, prevStart:Number = this.cachedStartTime, prevTimeScale:Number = this.cachedTimeScale, tween:TweenCore, isComplete:Boolean, rendered:Boolean, repeated:Boolean, next:TweenCore, dur:Number, prevPaused:Boolean = this.cachedPaused;
  425. if (time >= totalDur) {
  426. if (_rawPrevTime <= totalDur && _rawPrevTime != time) {
  427. if (!this.cachedReversed && this.yoyo && _repeat % 2 != 0) {
  428. forceChildrenToBeginning(0, suppressEvents);
  429. this.cachedTime = 0;
  430. } else {
  431. forceChildrenToEnd(this.cachedDuration, suppressEvents);
  432. this.cachedTime = this.cachedDuration;
  433. }
  434. this.cachedTotalTime = totalDur;
  435. isComplete = !this.hasPausedChild();
  436. rendered = true;
  437. if (this.cachedDuration == 0 && isComplete && (time == 0 || _rawPrevTime < 0)) { //In order to accommodate zero-duration timelines, we must discern the momentum/direction of time in order to render values properly when the "playhead" goes past 0 in the forward direction or lands directly on it, and also when it moves past it in the backward direction (from a postitive time to a negative time).
  438. force = true;
  439. }
  440. }
  441. } else if (time <= 0) {
  442. if (time < 0) {
  443. this.active = false;
  444. if (this.cachedDuration == 0 && _rawPrevTime > 0) { //In order to accommodate zero-duration timelines, we must discern the momentum/direction of time in order to render values properly when the "playhead" goes past 0 in the forward direction or lands directly on it, and also when it moves past it in the backward direction (from a postitive time to a negative time).
  445. force = true;
  446. isComplete = true;
  447. }
  448. }
  449. if (_rawPrevTime >= 0 && _rawPrevTime != time) {
  450. this.cachedTotalTime = 0;
  451. forceChildrenToBeginning(0, suppressEvents);
  452. this.cachedTime = 0;
  453. rendered = true;
  454. if (this.cachedReversed) {
  455. isComplete = true;
  456. }
  457. }
  458. } else {
  459. this.cachedTotalTime = this.cachedTime = time;
  460. }
  461. _rawPrevTime = time;
  462. if (_repeat != 0) {
  463. var cycleDuration:Number = this.cachedDuration + _repeatDelay;
  464. if (isComplete) {
  465. if (this.yoyo && _repeat % 2) {
  466. this.cachedTime = 0;
  467. }
  468. } else if (time > 0) {
  469. var prevCycles:int = _cyclesComplete;
  470. _cyclesComplete = int(this.cachedTotalTime / cycleDuration);
  471. if (_cyclesComplete == this.cachedTotalTime / cycleDuration) {
  472. _cyclesComplete--; //otherwise when rendered exactly at the end time, it will act as though it is repeating (at the beginning)
  473. }
  474. if (prevCycles != _cyclesComplete) {
  475. repeated = true;
  476. }
  477. this.cachedTime = ((this.cachedTotalTime / cycleDuration) - _cyclesComplete) * cycleDuration; //originally this.cachedTotalTime % cycleDuration but floating point errors caused problems, so I normalized it. (4 % 0.8 should be 0 but Flash reports it as 0.79999999!)
  478. if (this.yoyo && _cyclesComplete % 2) {
  479. this.cachedTime = this.cachedDuration - this.cachedTime;
  480. } else if (this.cachedTime >= this.cachedDuration) {
  481. this.cachedTime = this.cachedDuration;
  482. }
  483. if (this.cachedTime < 0) {
  484. this.cachedTime = 0;
  485. }
  486. }
  487. if (repeated && !isComplete && (this.cachedTime != prevTime || force)) {
  488. /*
  489. make sure children at the end/beginning of the timeline are rendered properly. If, for example,
  490. a 3-second long timeline rendered at 2.9 seconds previously, and now renders at 3.2 seconds (which
  491. would get transated to 2.8 seconds if the timeline yoyos or 0.2 seconds if it just repeats), there
  492. could be a callback or a short tween that's at 2.95 or 3 seconds in which wouldn't render. So
  493. we need to push the timeline to the end (and/or beginning depending on its yoyo value).
  494. */
  495. var forward:Boolean = Boolean(!this.yoyo || (_cyclesComplete % 2 == 0));
  496. var prevForward:Boolean = Boolean(!this.yoyo || (prevCycles % 2 == 0));
  497. var wrap:Boolean = Boolean(forward == prevForward);
  498. if (prevCycles > _cyclesComplete) {
  499. prevForward = !prevForward;
  500. }
  501. if (prevForward) {
  502. prevTime = forceChildrenToEnd(this.cachedDuration, suppressEvents);
  503. if (wrap) {
  504. prevTime = forceChildrenToBeginning(0, true);
  505. }
  506. } else {
  507. prevTime = forceChildrenToBeginning(0, suppressEvents);
  508. if (wrap) {
  509. prevTime = forceChildrenToEnd(this.cachedDuration, true);
  510. }
  511. }
  512. rendered = false;
  513. }
  514. }
  515. if (this.cachedTime == prevTime && !force) {
  516. return;
  517. } else if (!this.initted) {
  518. this.initted = true;
  519. }
  520. if (prevTime == 0 && this.cachedTotalTime != 0 && !suppressEvents) {
  521. if (this.vars.onStart) {
  522. this.vars.onStart.apply(null, this.vars.onStartParams);
  523. }
  524. if (_dispatcher) {
  525. _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.START));
  526. }
  527. }
  528. if (rendered) {
  529. //already rendered, so ignore
  530. } else if (this.cachedTime - prevTime > 0) {
  531. tween = _firstChild;
  532. while (tween) {
  533. next = tween.nextNode; //record it here because the value could change after rendering...
  534. if (this.cachedPaused && !prevPaused) { //in case a tween pauses the timeline when rendering
  535. break;
  536. } else if (tween.active || (!tween.cachedPaused && tween.cachedStartTime <= this.cachedTime && !tween.gc)) {
  537. if (!tween.cachedReversed) {
  538. tween.renderTime((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale, suppressEvents, false);
  539. } else {
  540. dur = (tween.cacheIsDirty) ? tween.totalDuration : tween.cachedTotalDuration;
  541. tween.renderTime(dur - ((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale), suppressEvents, false);
  542. }
  543. }
  544. tween = next;
  545. }
  546. } else {
  547. tween = _lastChild;
  548. while (tween) {
  549. next = tween.prevNode; //record it here because the value could change after rendering...
  550. if (this.cachedPaused && !prevPaused) { //in case a tween pauses the timeline when rendering
  551. break;
  552. } else if (tween.active || (!tween.cachedPaused && tween.cachedStartTime <= prevTime && !tween.gc)) {
  553. if (!tween.cachedReversed) {
  554. tween.renderTime((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale, suppressEvents, false);
  555. } else {
  556. dur = (tween.cacheIsDirty) ? tween.totalDuration : tween.cachedTotalDuration;
  557. tween.renderTime(dur - ((this.cachedTime - tween.cachedStartTime) * tween.cachedTimeScale), suppressEvents, false);
  558. }
  559. }
  560. tween = next;
  561. }
  562. }
  563. if (_hasUpdate && !suppressEvents) {
  564. this.vars.onUpdate.apply(null, this.vars.onUpdateParams);
  565. }
  566. if (_hasUpdateListener && !suppressEvents) {
  567. _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.UPDATE));
  568. }
  569. if (isComplete && (prevStart == this.cachedStartTime || prevTimeScale != this.cachedTimeScale) && (totalDur >= this.totalDuration || this.cachedTime == 0)) { //if one of the tweens that was rendered altered this timeline's startTime (like if an onComplete reversed the timeline) or if it added more tweens to the timeline, we shouldn't run complete() because it probably isn't complete. If it is, don't worry, because whatever call altered the startTime would have called complete() if it was necessary at the new time. The only exception is the timeScale property.
  570. complete(true, suppressEvents);
  571. } else if (repeated && !suppressEvents) {
  572. if (this.vars.onRepeat) {
  573. this.vars.onRepeat.apply(null, this.vars.onRepeatParams);
  574. }
  575. if (_dispatcher) {
  576. _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.REPEAT));
  577. }
  578. }
  579. }
  580. /**
  581. * Forces the timeline to completion.
  582. *
  583. * @param skipRender to skip rendering the final state of the timeline, set skipRender to true.
  584. * @param suppressEvents If true, no events or callbacks will be triggered for this render (like onComplete, onUpdate, onReverseComplete, etc.)
  585. */
  586. override public function complete(skipRender:Boolean=false, suppressEvents:Boolean=false):void {
  587. super.complete(skipRender, suppressEvents);
  588. if (_dispatcher && !suppressEvents) {
  589. if (this.cachedReversed && this.cachedTotalTime == 0 && this.cachedDuration != 0) {
  590. _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.REVERSE_COMPLETE));
  591. } else {
  592. _dispatcher.dispatchEvent(new TweenEvent(TweenEvent.COMPLETE));
  593. }
  594. }
  595. }
  596. /**
  597. * Returns the tweens/timelines that are currently active in the timeline.
  598. *
  599. * @param nested determines whether or not tweens and/or timelines that are inside nested timelines should be returned. If you only want the "top level" tweens/timelines, set this to false.
  600. * @param tweens determines whether or not tweens (TweenLite and TweenMax instances) should be included in the results
  601. * @param timelines determines whether or not timelines (TimelineLite and TimelineMax instances) should be included in the results
  602. * @return an Array of active tweens/timelines
  603. */
  604. public function getActive(nested:Boolean=true, tweens:Boolean=true, timelines:Boolean=false):Array {
  605. var a:Array = [], all:Array = getChildren(nested, tweens, timelines), i:int;
  606. var l:uint = all.length;
  607. var cnt:uint = 0;
  608. for (i = 0; i < l; i++) {
  609. if (TweenCore(all[i]).active) {
  610. a[cnt++] = all[i];
  611. }
  612. }
  613. return a;
  614. }
  615. /** @inheritDoc **/
  616. override public function invalidate():void {
  617. _repeat = (this.vars.repeat) ? Number(this.vars.repeat) : 0;
  618. _repeatDelay = (this.vars.repeatDelay) ? Number(this.vars.repeatDelay) : 0;
  619. this.yoyo = Boolean(this.vars.yoyo == true);
  620. if (this.vars.onCompleteListener != null || this.vars.onUpdateListener != null || this.vars.onStartListener != null || this.vars.onRepeatListener != null || this.vars.onReverseCompleteListener != null) {
  621. initDispatcher();
  622. }
  623. setDirtyCache(true);
  624. super.invalidate();
  625. }
  626. /**
  627. * Returns the next label (if any) that occurs AFTER the time parameter. It makes no difference
  628. * if the timeline is reversed. A label that is positioned exactly at the same time as the <code>time</code>
  629. * parameter will be ignored.
  630. *
  631. * @param time Time after which the label is searched for. If you do not pass a time in, the currentTime will be used.
  632. * @return Name of the label that is after the time passed to getLabelAfter()
  633. */
  634. public function getLabelAfter(time:Number=NaN):String {
  635. if (!time && time != 0) { //faster than isNan()
  636. time = this.cachedTime;
  637. }
  638. var labels:Array = getLabelsArray();
  639. var l:uint = labels.length;
  640. for (var i:int = 0; i < l; i++) {
  641. if (labels[i].time > time) {
  642. return labels[i].name;
  643. }
  644. }
  645. return null;
  646. }
  647. /**
  648. * Returns the previous label (if any) that occurs BEFORE the time parameter. It makes no difference
  649. * if the timeline is reversed. A label that is positioned exactly at the same time as the <code>time</code>
  650. * parameter will be ignored.
  651. *
  652. * @param time Time before which the label is searched for. If you do not pass a time in, the currentTime will be used.
  653. * @return Name of the label that is before the time passed to getLabelBefore()
  654. */
  655. public function getLabelBefore(time:Number=NaN):String {
  656. if (!time && time != 0) { //faster than isNan()
  657. time = this.cachedTime;
  658. }
  659. var labels:Array = getLabelsArray();
  660. var i:int = labels.length;
  661. while (--i > -1) {
  662. if (labels[i].time < time) {
  663. return labels[i].name;
  664. }
  665. }
  666. return null;
  667. }
  668. /** @private Returns an Array of label objects, each with a "time" and "name" property, in the order that they occur in the timeline. **/
  669. protected function getLabelsArray():Array {
  670. var a:Array = [];
  671. for (var p:String in _labels) {
  672. a[a.length] = {time:_labels[p], name:p};
  673. }
  674. a.sortOn("time", Array.NUMERIC);
  675. return a;
  676. }
  677. //---- EVENT DISPATCHING ----------------------------------------------------------------------------------------------------------
  678. /** @private **/
  679. protected function initDispatcher():void {
  680. if (_dispatcher == null) {
  681. _dispatcher = new EventDispatcher(this);
  682. }
  683. if (this.vars.onStartListener is Function) {
  684. _dispatcher.addEventListener(TweenEvent.START, this.vars.onStartListener, false, 0, true);
  685. }
  686. if (this.vars.onUpdateListener is Function) {
  687. _dispatcher.addEventListener(TweenEvent.UPDATE, this.vars.onUpdateListener, false, 0, true);
  688. _hasUpdateListener = true;
  689. }
  690. if (this.vars.onCompleteListener is Function) {
  691. _dispatcher.addEventListener(TweenEvent.COMPLETE, this.vars.onCompleteListener, false, 0, true);
  692. }
  693. if (this.vars.onRepeatListener is Function) {
  694. _dispatcher.addEventListener(TweenEvent.REPEAT, this.vars.onRepeatListener, false, 0, true);
  695. }
  696. if (this.vars.onReverseCompleteListener is Function) {
  697. _dispatcher.addEventListener(TweenEvent.REVERSE_COMPLETE, this.vars.onReverseCompleteListener, false, 0, true);
  698. }
  699. }
  700. /** @private **/
  701. public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void {
  702. if (_dispatcher == null) {
  703. initDispatcher();
  704. }
  705. if (type == TweenEvent.UPDATE) {
  706. _hasUpdateListener = true;
  707. }
  708. _dispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference);
  709. }
  710. /** @private **/
  711. public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void {
  712. if (_dispatcher != null) {
  713. _dispatcher.removeEventListener(type, listener, useCapture);
  714. }
  715. }
  716. /** @private **/
  717. public function hasEventListener(type:String):Boolean {
  718. return (_dispatcher == null) ? false : _dispatcher.hasEventListener(type);
  719. }
  720. /** @private **/
  721. public function willTrigger(type:String):Boolean {
  722. return (_dispatcher == null) ? false : _dispatcher.willTrigger(type);
  723. }
  724. /** @private **/
  725. public function dispatchEvent(e:Event):Boolean {
  726. return (_dispatcher == null) ? false : _dispatcher.dispatchEvent(e);
  727. }
  728. //---- GETTERS / SETTERS -------------------------------------------------------------------------------------------------------
  729. /**
  730. * Value between 0 and 1 indicating the overall progress of the timeline according to its <code>totalDuration</code>
  731. * where 0 is at the beginning, 0.5 is halfway finished, and 1 is finished. <code>currentProgress</code>,
  732. * by contrast, describes the progress according to the timeline's duration which does not
  733. * include repeats and repeatDelays. For example, if a TimelineMax instance is set
  734. * to repeat once, at the end of the first cycle <code>totalProgress</code> would only be 0.5
  735. * whereas <code>currentProgress</code> would be 1. If you tracked both properties over the course of the
  736. * tween, you'd see <code>currentProgress</code> go from 0 to 1 twice (once for each cycle) in the same
  737. * time it takes the <code>totalProgress</code> property to go from 0 to 1 once.
  738. **/
  739. public function get totalProgress():Number {
  740. return this.cachedTotalTime / this.totalDuration;
  741. }
  742. public function set totalProgress(n:Number):void {
  743. setTotalTime(this.totalDuration * n, false);
  744. }
  745. /**
  746. * Duration of the timeline in seconds (or frames for frames-based timelines) including any repeats
  747. * or repeatDelays. "duration", by contrast, does NOT include repeats and repeatDelays.
  748. **/
  749. override public function get totalDuration():Number {
  750. if (this.cacheIsDirty) {
  751. var temp:Number = super.totalDuration; //just forces refresh
  752. //Instead of Infinity, we use 999999999999 so that we can accommodate reverses.
  753. this.cachedTotalDuration = (_repeat == -1) ? 999999999999 : this.cachedDuration * (_repeat + 1) + (_repeatDelay * _repeat);
  754. }
  755. return this.cachedTotalDuration;
  756. }
  757. /** @inheritDoc **/
  758. override public function set currentTime(n:Number):void {
  759. if (_cyclesComplete == 0) {
  760. setTotalTime(n, false);
  761. } else if (this.yoyo && (_cyclesComplete % 2 == 1)) {
  762. setTotalTime((this.duration - n) + (_cyclesComplete * (this.cachedDuration + _repeatDelay)), false);
  763. } else {
  764. setTotalTime(n + (_cyclesComplete * (this.duration + _repeatDelay)), false);
  765. }
  766. }
  767. /** Number of times that the timeline should repeat; -1 repeats indefinitely. **/
  768. public function get repeat():int {
  769. return _repeat;
  770. }
  771. public function set repeat(n:int):void {
  772. _repeat = n;
  773. setDirtyCache(true);
  774. }
  775. /** Amount of time in seconds (or frames for frames-based timelines) between repeats **/
  776. public function get repeatDelay():Number {
  777. return _repeatDelay;
  778. }
  779. public function set repeatDelay(n:Number):void {
  780. _repeatDelay = n;
  781. setDirtyCache(true);
  782. }
  783. /** The closest label that is at or before the current time. **/
  784. public function get currentLabel():String {
  785. return getLabelBefore(this.cachedTime + 0.00000001);
  786. }
  787. }
  788. }