利用GreenSock Tweening Platform製作動畫

因為馬老師剛開始利用程式製作補間動畫的Class是Tweener,所以前面介紹了很多篇這方面的文章,但當然這方面的Class不是只有Tweener而已,所以接下來介紹一個目前發展起來比Tweener還要棒很多的Class,它是由GreenSock研發的Tweening Platform(補間平台),其中包含了:「TweenNano」、「TweenLite」、「TweenMax」、「TimelineLite」、「TimelineMax」。

為什麼說他發展得比較好呢?除了Tweener能做到的幾乎它都可以以外,也因為Tweener已經停止開發,所以未來將不會有新增的功能,但TweenMax還在不斷的更新中,在官網還有以下的比較案例:

各種補間動畫 速度測試

從上面的案例可以看出來利用GreenSock所研發的Tweening Platform的執行效能會比其他的好(FPS越高越好),所以接下來就來看看GreenSock Tweening Platform的簡介。

TweenNano、TweenLite與TweenMax算是同樣功能,但在製作後檔案容量是TweenNano<TweenLite<TweenMax,也就是說利用TweenNano所製作出來的動畫容量是最小的,舉個例來說,像這樣的動畫效果,TweenNano製作後swf大小為:5KB、TweenLite:8KB、TweenMax:21KB,不過在功能上面也是TweenNano<TweenLite<TweenMax,也就是說TweenMax可以掌控的效果比較多,也更具有彈性,例如:TweenNano就沒有辦法執行:pause()、play()、restart()…等,而TweenLite沒辦法執行:貝茲曲線運動、濾鏡…等,所以要用哪個版本的Tween,端看想要製作的動畫效果來考量,官方也有針對此三者製作比較表供大家參考。

另外TimelineLite和TimelineMax算是同樣功能,但看到後面的英文單字應該可以了解與上述具有相同的關聯,而這方面的Class是可以掌握時間軸上面的變化,在Tweener中,我們只能用Delay來控制動畫先後順序,而在GreenSock所研發的Tweening Platform中則可以利用TimlinelineLite或TimelineMax來處理。

馬上來介紹有關這個Class的一些使用方式,與Tweener一樣的是必須先下載備用載點),然後在需要使用的Flash檔案中import該Class,下載解壓後會有以下的資料夾:

  • badges:GreenSock圖標。
  • com:主要Class資料夾。
  • demo_swfs:裡面有很多swf的展示,對於想要了解本Class非常有幫助。
  • docs:參考文件。

在import時,看你想要使用的Class來import,例如需要使用TweenNano則:

import com.greensock.TweenNano;

若需同時使用TweenLite和TweenMax則:

import com.greensock.TweenLite;
import com.greensock.TweenMax;

想偷懶,則:(別擔心,Flash只會內嵌有使用到的部分)

import com.greensock.*;

至於製作補間的程式碼,其實官方就有製作swf來給大家參考,這邊也把官方的範例放進來給大家參考:

基礎動畫製作 範例檔

上面的案例可以讓你測試動畫效果,下方也會產生該段動畫的程式碼供你使用,實在是非常方便。另外關於Tween的語法也可以改成下面這種版本:

TweenLite.from(mc, 1.5, {y:0, alpha:0});

一個是告訴動畫要去哪,另一個是告訴動畫要從哪開始變化,關於Tweener可以使用的delay、onComplete、onStart、onUpdate…等,這個Class也都可以使用,例如:

TweenLite.to(mc, 1.5, {x:100, ease:Elastic.easeOut, delay:1, onComplete:okFn});
function okFn() {
    trace("動畫執行完畢");
}

這個Class還有很多特別的動畫效果,例如:濾鏡、短距離旋轉、貝茲曲線、聲音、色彩變換…等,大家也可以參考官方製作的swf來參考動畫效果與取得程式碼:

特殊動畫效果 範例圖

在動畫控制上面可以使用如下的程式碼來控制動畫:

var myTween:TweenLite = new TweenLite(mc, 1, {x:100, y:100});

myTween.pause();
//暫停動畫播放

myTween.resume();
//恢復動畫播放

myTween.reverse();
//反向播放

myTween.play();
//播放動畫

myTween.restart();
//重播動畫

myTween.invalidate();
//移除補間並使元件恢復原始狀態

myTween.kill();
//清除補間動畫

TweenLite.killTweensOf(mc);
//清除所有物件之補間動畫

以上是有關GreenSock Tweening的介紹,接下來介紹有關TimelineLite與TimelingMax的部分。

就像上面有提到在Tweener中我們如果希望三個元件在不同的時間點開始移動,就只能使用delay或是另外寫程式來控制,現在我們可以使用Timeline相關的Class來完成這樣的任務,甚至還可以讓時間軸倒著播放也沒問題,以下就是有關TimelineLite的官方範例:

TimelineLite 範例檔

另外是TimelineMax的範例檔,供大家參考:

TimelineMax 範例檔

以上就是針對GreenSock Tweening Platform大致的介紹,建議有空可以前往官網鑽研更多其他的功能,另外其實GreenSock另外還有TransformManagerLoaderMax,各位也可以先參考官網文章或是未來再跟大家分享我的使用心得。

註:本範例所使用的範例版權屬於GreenSock公司所有。

You may also like...

24,630 Responses

  1. JustinTam表示:

    doxycyline online: cost doxycycline – doxycycline 500mg price

  2. VirgilBlawl表示:

    buy zithromax without presc ZithroPharm zithromax buy online no prescription

  3. Billfut表示:

    darknet markets onion darknet links

  4. Briantrozy表示:

    doxycycline gel: DoxHealthPharm – doxycycline nz cost

  5. JustinTam表示:

    average cost of generic zithromax: Zithro Pharm – buy generic zithromax online

  6. BrandonJag表示:

    buy zithromax online cheap: ZithroPharm – purchase zithromax z-pak

  7. VirgilBlawl表示:

    doxycycline canadian pharmacy doxycycline online uk doxycycline generic price

  8. JustinTam表示:

    get cheap clomid without a prescription: ClmHealthPharm – cost cheap clomid without dr prescription

  9. Briantrozy表示:

    how to get zithromax over the counter: generic zithromax online paypal – generic zithromax over the counter

  10. Briantrozy表示:

    zithromax 600 mg tablets: Zithro Pharm – zithromax cost

  11. Jerrynurce表示:

    Lucky Jet – твой шанс на большие выигрыши!
    Попробуй захватывающую краш-игру прямо сейчас! Регистрируйся и получи бонус до 500% на первый депозит с промокодом: LuckyJetTeam.
    лаки джет официальный сайт
    Об игре
    Lucky Jet — это не просто игра, а захватывающее приключение, в котором каждый момент может стать решающим! Эта краш-игра бросает вызов вашим инстинктам и способности быстро принимать решения. В основе игры — динамичная механика, где игроки ставят на рост коэффициента, но задача не в том, чтобы ждать до последнего, а вовремя вывести свой выигрыш, прежде чем персонаж взлетит слишком высоко и случится крах.

    Чем выше коэффициент, тем более значительная награда! Но не забывайте: в этом азартном путешествии важен каждый момент, ведь именно ваше решение о выводе решит, насколько велик будет ваш выигрыш. Это не просто игра, а настоящее испытание на скорость и удачу! Простые правила, быстрые раунды и реальные выигрыши – вот почему игроки выбирают Lucky Jet.

    Бонусы и промокоды в Lucky Jet
    В Lucky Jet вас ждут щедрые бонусы и эксклюзивные промокоды, которые помогут увеличить ваш баланс и продлить удовольствие от игры! Мы ценим активных игроков и регулярно запускаем новые акции, чтобы сделать ваш игровой процесс еще выгоднее.

    Актуальные бонусные предложения
    Бонус 500% на первый депозит
    Используйте промокод LuckyJetTeam при пополнении счета и получите увеличение депозита в 5 раз! Это отличная возможность начать игру с солидным запасом.
    Еженедельные акции и фриспины
    Чем больше вы играете, тем больше подарков получаете! Участвуйте в регулярных промо-акциях и получайте фриспины, бонусные деньги и дополнительные награды за активность.
    Кэшбэк до 10%
    Проиграли? Не беда! В Lucky Jet вы можете вернуть часть потерянных средств благодаря системе кэшбэка. Еженедельно вам будет начисляться до 10% возврата от проигранных ставок.
    Следите за новыми акциями! Мы постоянно обновляем бонусные предложения, поэтому не упустите возможность воспользоваться самыми выгодными промо. Подписывайтесь на новости и следите за актуальными акциями, чтобы всегда быть в выигрыше!

    Используйте бонусы и повышайте свои шансы на победу в Lucky Jet!

    Как начать играть в Lucky Jet
    Готовы испытать удачу и выиграть по-крупному? Следуйте этим простым шагам:

    Зарегистрируйтесь на официальном сайте 1win. Процесс регистрации занимает всего пару минут.
    Пополните счет удобным для вас способом: банковской картой, электронными кошельками или даже криптовалютой.
    Откройте Lucky Jet в разделе казино и приготовьтесь к динамичному игровому процессу.
    Сделайте ставку и следите за ростом коэффициента. Чем выше он поднимается – тем больше ваш потенциальный выигрыш.
    Выведите выигрыш до того, как Lucky Jet взлетит! Главное – не жадничать и вовремя остановиться, иначе ставка сгорит.
    Используйте стратегии, анализируйте предыдущие раунды и комбинируйте ставки, чтобы увеличить свои шансы на победу!

  12. Briantrozy表示:

    where can i buy amoxicillin over the counter: AmoHealthPharm – cost of amoxicillin 30 capsules

  13. Utiliza el codigo de bonificacion de 1xCasino: “1XBUM” para obtener un bono VIP de hasta €1950 mas 150 giros gratis en el casino y un 200% hasta €130 en apuestas deportivas. Introduce nuestro codigo promocional para 1x Casino 2025 en el formulario de registro y reclama bonos exclusivos para el casino y las apuestas deportivas. Bonificacion sin deposito de 1xCasino de $2420. Es necesario registrarse, confirmar tu correo electronico e ingresar el codigo promocional.

    1xbet bono sin deposito

  14. Kevinalgon表示:

    Scores of unexploded World War II bombs discovered under children’s playground
    lucky jet играть
    Scores of unexploded bombs dating from World War II have been recovered from a children’s playground in northern England after a chance discovery.

    Local officials in the town of Wooler, Northumberland called in bomb disposal experts after workers involved in a planned overhaul of Scotts Play Park found unexploded ordnance, the parish council said in a statement sent to CNN on Monday.

    Two bombs were initially removed by the British Army, the UK Ministry of Defense said in a statement. The parish council was then advised that a full survey of the area was required, according to a council spokesperson.
    Bomb disposal company Brimstone Site Investigation then uncovered 65 10-pound practice bombs and smoke cartridges on the first day of works, with a further 90 practice bombs recovered on the second day.

    The company told CNN that the bombs date from World War II.

    According to the parish council, all of the bombs need to be found and removed before the park can be reopened. It said 174 devices had been found so far.

  15. Roberttic表示:

    https://amohealthpharm.shop/# amoxicillin where to get

  16. MichaelBiady表示:

    Cute baby animals bring visitors to zoos and aquariums. What happens when they grow up?
    арбитраж трафика каналы
    One of the best things that can happen to a zoo or aquarium is for one of their resident animals to go viral.

    Just look at the multi-hour-long lines to see Moo Deng, a pygmy hippo in Thailand who has become an internet sensation following her July 2024 birth. The sassy animal is now a full-on brand, with Khao Kheow Open Zoo selling Moo Deng merchandise and even releasing a single “by” the hippo in multiple languages.

    Meanwhile, Pesto — a baby king penguin who was eating more fish than his parents by the time he was a few weeks old — is also an online celebrity, with human stars like Olivia Rodrigo and Katy Perry stopping by to meet him.

    But what happens when these cute animals become, well, less cute? The Sea Life Melbourne aquarium has already been planning for the next phase of Pesto’s life — and answering questions from the public about his changing appearance.

    It’s normal for king penguins to lose their feathers by the time they’re about a year old and become confident swimmers. As a result, a spokesperson for the aquarium says, guests have started asking why Pesto looks different — or why they can’t find him at all.

    “We are getting a few guests thinking we have moved him off display completely,” says the spokesperson. “Most of the team’s time is spent pointing him out to guests because he looks so different now.”
    The bottom line is that cute baby animals make money.

    Admission tickets are only the beginning. Many zoos and aquariums offer special “behind the scenes” or “zookeeper for a day” packages at much higher prices. At Sea Life Melbourne, standard entry tickets for adults start at $51, while the Penguin Passport — which include a 45-minute tour of the birds’ area and a look at how their food is prepared — is $199.

    The real jackpot, though, is merchandise. Stuffed animals, T-shirts, fridge magnets, keychains, kids’ books and other branded products are a major way for zoos and aquariums to make money.

  17. Phillipedugs表示:

    Look of the Week: Kendrick Lamar’s Super Bowl pants signal the return of flares
    Кракен тор
    This year’s Super Bowl halftime show was hardly a fashion extravaganza, with headliner Kendrick Lamar keeping things simple in a backwards cap and motorbike-style varsity jacket, which he kept on throughout.

    And without the costume-change roulette we’ve come to expect of halftime shows, the internet fixated on one item in particular: his jeans.

    While not quite the bell-bottoms of decades past (the 1970s and the 2000s, specifically), the Compton-born rapper’s washed denim pants flared out at the knee and dragged beneath his heels along the stage at Caesars Superdrome in New Orleans. His silhouette stood in stark contrast to that of record producer Mustard, who made a brief cameo in a pair of outsized jeans straight from the West Coast hip-hop playbook.
    Opinions were, as ever, divided on social media. Some users described Lamar’s flares as “women’s jeans” and “Hannah Montana pants,” earning him comparisons to everyone from Jennifer Aniston to country singer Lainey Wilson. Others joked that their moms were looking for a similar pair or that they nodded to millennials, for whom flares were a teenage staple.

    But those suggesting his style was outdated, or gender-inappropriate, may not have been paying attention to the recent resurgence of flares — in both womenswear and menswear. After all, Lamar’s jeans were designed by one of the most influential figures in modern fashion, Celine’s former creative director Hedi Slimane, before he departed the French label in October.

  18. MbikolkolTef表示:

    Utiliza el codigo de bonificacion de 1xCasino: “1XBUM” para obtener un bono VIP de hasta €1950 mas 150 giros gratis en el casino y un 200% hasta €130 en apuestas deportivas. Introduce nuestro codigo promocional para 1x Casino 2025 en el formulario de registro y reclama bonos exclusivos para el casino y las apuestas deportivas. Bonificacion sin deposito de 1xCasino de $2420. Es necesario registrarse, confirmar tu correo electronico e ingresar el codigo promocional.

    1xCasino codigo promocional brasil

  19. Kennethphink表示:

    Scores of unexploded World War II bombs discovered under children’s playground
    лаки джет сайт
    Scores of unexploded bombs dating from World War II have been recovered from a children’s playground in northern England after a chance discovery.

    Local officials in the town of Wooler, Northumberland called in bomb disposal experts after workers involved in a planned overhaul of Scotts Play Park found unexploded ordnance, the parish council said in a statement sent to CNN on Monday.

    Two bombs were initially removed by the British Army, the UK Ministry of Defense said in a statement. The parish council was then advised that a full survey of the area was required, according to a council spokesperson.
    Bomb disposal company Brimstone Site Investigation then uncovered 65 10-pound practice bombs and smoke cartridges on the first day of works, with a further 90 practice bombs recovered on the second day.

    The company told CNN that the bombs date from World War II.

    According to the parish council, all of the bombs need to be found and removed before the park can be reopened. It said 174 devices had been found so far.

  20. MichaelDromb表示:

    Look of the Week: Kendrick Lamar’s Super Bowl pants signal the return of flares
    kraken войти
    This year’s Super Bowl halftime show was hardly a fashion extravaganza, with headliner Kendrick Lamar keeping things simple in a backwards cap and motorbike-style varsity jacket, which he kept on throughout.

    And without the costume-change roulette we’ve come to expect of halftime shows, the internet fixated on one item in particular: his jeans.

    While not quite the bell-bottoms of decades past (the 1970s and the 2000s, specifically), the Compton-born rapper’s washed denim pants flared out at the knee and dragged beneath his heels along the stage at Caesars Superdrome in New Orleans. His silhouette stood in stark contrast to that of record producer Mustard, who made a brief cameo in a pair of outsized jeans straight from the West Coast hip-hop playbook.
    Opinions were, as ever, divided on social media. Some users described Lamar’s flares as “women’s jeans” and “Hannah Montana pants,” earning him comparisons to everyone from Jennifer Aniston to country singer Lainey Wilson. Others joked that their moms were looking for a similar pair or that they nodded to millennials, for whom flares were a teenage staple.

    But those suggesting his style was outdated, or gender-inappropriate, may not have been paying attention to the recent resurgence of flares — in both womenswear and menswear. After all, Lamar’s jeans were designed by one of the most influential figures in modern fashion, Celine’s former creative director Hedi Slimane, before he departed the French label in October.

  21. Ozzyfut表示:

    dark web market links dark markets

  22. BrandonJag表示:

    how to buy amoxycillin: Amo Health Pharm – where can i buy amoxocillin

  23. JustinTam表示:

    buy amoxicillin online without prescription: AmoHealthPharm – medicine amoxicillin 500mg

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。