利用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...

27,097 Responses

  1. WilliamTaurl表示:

    Xavier completes thrilling comeback, Mount St. Mary’s advances as men’s First Four comes to a close
    changenow
    Wednesday saw the men’s First Four come to a close which means only one thing: the 64-team bracket is officially set following No. 11 Xavier’s thrilling come from behind win over No. 11 Texas and No. 16 Mount St. Mary’s victory over No. 16 American in Dayton, Ohio.

    The Musketeers trailed by as many as 13 points, but their offense came alive in the second half behind guard Marcus Foster and forward Zach Freemantle to down the Longhorns 86-80.

    The senior Foster scored a team-high 22 points while Freemantle, on his way to 15 points, threw down a dunk with a second left to seal the comeback win and ignite the fans at UD Arena, which is just over 50 miles away from campus in Cincinnati, Ohio.

    With just under four minutes remaining, Xavier went on an 8-2 run to take a 78-74 lead, their first since the early going of the first half.

    Musketeers head coach Sean Miller crowned Wednesday’s game as “one of the best” he’s been a part of.

    “I thought we were dead in the water two different times,” Miller told the truTV broadcast after the game. “But that’s the one thing about our team — the resiliency of our group has always won out for us. Just when you thought we weren’t gonna make the tournament, we kept winning. Even in this game, just when you’re like, ‘It’s not gonna work out,’ we have a funny way of staying with it.”

    The Longhorns did not go down without a fight as guard Tre Johnson scored a game-high 23 points in the loss.

    Xavier will face No. 6 Illinois in the first round on Friday at the Fiserv Forum in Milwaukee.

  2. Williszew表示:

    https://interpharmonline.com/# canadian mail order pharmacy

  3. Montebeera表示:

    IndiaMedFast.com online medicine shopping in india india online pharmacy store

  4. Williszew表示:

    https://mexicanpharminter.shop/# Mexican Pharm International

  5. Arthurhow表示:

    http://indiamedfast.com/# online pharmacy india
    best canadian pharmacy

  6. JamesGag表示:

    reliable mexican pharmacies: mexican pharmacy online store – reliable mexican pharmacies

  7. KellyIroke表示:

    The fish collectors hoping to save rare species from extinction
    phantom wallet
    In the rural town of Petersham, Massachusetts, 78-year-old Peter George keeps 1,000 fish in his basement.

    “Baseball, sex, fish,” he says, listing his life’s great loves. “My single greatest attribute is that I am passionate about things. That sort of defines me.”

    All of George’s fish are endangered Rift Lake cichlids: colorful, freshwater fish native to the Great Lakes of East Africa. Inside his 42 tanks, expertly squeezed into a single subterranean room, the fish shimmer under artificial lights, knowing nothing of the expansive waters in which their ancestors once swam, thousands of miles away.

    Due to pollution, climate change and overfishing, freshwater fish are thought to be the second most endangered vertebrates in the world. In Lake Victoria, a giant lake shared between Kenya, Uganda and Tanzania, over a quarter of endemic species, including countless cichlids, are either critically endangered or extinct.

    But for some species, there is still hope. A community of rare fish enthusiasts collect endangered species of freshwater fish from the lakes and springs of East Africa, Mexico and elsewhere, and preserve them in their personal fish tanks in the hope that they might one day be reintroduced in the wild.

    “I’m a hard ass,” George says. “There is hope.”
    Insurance
    George has been collecting fish since 1948 when, as a four-year-old in the Bronx, he would look after his grandmother’s rainbow fish. He soon developed “multiple tank syndrome” – a colloquial term used by fish collectors to denote the spiral commonly experienced after acquiring one’s first tank, which involves the sufferer buying many more tanks within a short space of time. He has not stopped collecting since.

    Now, George sees himself as a conservationist; his tanks contain what is known as “insurance populations” – populations of endangered fish that are likely to go extinct in their natural habitats. He believes that when the time is right, they can be taken from his collection and returned to their homes. “I would never accept the fact that they couldn’t be reintroduced,” he says.

  8. Georgewhend表示:

    legal canadian pharmacy online: Online pharmacy USA – prescription drugs canada buy online

  9. Williamevads表示:

    A librarian ran off with a yacht captain in the summer of 1968. It was the start of an incredible love story
    metamask
    The first time Beverly Carriveau saw Bob Parsons, she felt like a “thunderbolt” passed between them.

    “This man stepped out of a taxi, and we both just stared at each other,” Beverly tells CNN Travel today. “You have to remember, this is the ‘60s. Girls didn’t stare at men. But it was a thunderbolt.”

    It was June 1968. Beverly was a 23-year-old Canadian university librarian on vacation in Mazatlan, Mexico, with a good friend in tow.

    Beverly had arrived in Mazatlan that morning. She’d been blown away by the Pacific Ocean views, the colorful 19th-century buildings, the palm trees.

    Now, Beverly was browsing the hotel gift store, admiring a pair of earrings, when she looked up and spotted the man getting out of the taxi. The gift shop was facing the parking lot, and there he was.

    “I was riveted,” says Beverly. “He was tall, handsome…”

    Eventually, Beverly tore away her gaze, bought the earrings and dashed out of the store.

    “We locked eyes so long, I was embarrassed,” she says.

    No words had passed between them. They hadn’t even smiled at each other. But Beverly felt like she’d revealed something of herself. She felt like something had happened, but she couldn’t describe it.
    Beverly rushed to meet her friend, still feeling flustered. Over dinner in the hotel restaurant, Beverly confided in her friend about the “thunderbolt” moment.

    “I told my girlfriend, ‘Something just happened to me. I stared at this man, and I couldn’t help myself.’”

    Then, the server approached Beverly’s table.

    “He said, ‘I have some wine for you, from a man over there.’”

    The waiter was holding a bottle of white wine, indicating at the bar, which was packed with people.

    As a rule, Beverly avoided accepting drinks from men in bars. She never felt especially comfortable with the power dynamic — plus, she had a long-term partner back in Canada.

    “I had a serious boyfriend at home and thought my life was on course,” she says.

  10. Arthurhow表示:

    http://interpharmonline.com/# canadian pharmacy meds reviews
    canadian pharmacy 24h com safe

  11. Georgewhend表示:

    canadian online drugstore: fda approved canadian online pharmacies – my canadian pharmacy rx

  12. Arthurhow表示:

    https://indiamedfast.shop/# online pharmacy india
    buy canadian drugs

  13. JamesGag表示:

    best canadian pharmacy to buy from: most trusted canadian pharmacies online – canadian drugs pharmacy

  14. Montebeera表示:

    online medicine shopping in india buying prescription drugs from india India Med Fast

  15. JamesGag表示:

    canadian pharmacies that deliver to the us: Pharmacies in Canada that ship to the US – canada drugs online reviews

  16. kolajen nedir表示:

    web sitemizden kolajen satın alabilirsiniz ve faydalı bilgilere bakabilirsiniz.

  17. BryanbeS表示:

    Промокод Фонбет – это кодовые слова, например: MAX777, ввод которых при регистрации в БК Фонбет или в личном кабинете позволяет получить фрибеты, страховки ставок и другие специальные бонусы. Промокодом в беттинге называется комбинация букв и цифр, при вводе которых активируется бонус. Новым клиентам Фонбет предлагает приветственные фрибеты на сумму от 100 до 15 000 рублей.

    промокод fonbet на фрибет

  18. JamesGag表示:

    online medicine shopping in india: cheapest online pharmacy india – cheapest online pharmacy india

  19. Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
    Мы предлагаем:сервисные центры по ремонту техники в мск
    Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!

  20. the best thing you can do is to stop.エロ コスプレStopping at any time in pregnancy will help,

  21. Georgewhend表示:

    cheapest online pharmacy india: india pharmacy without prescription – cheapest online pharmacy india

  22. pdacenter.ru – сервис по ремонту бытовой техники
    Ремонт парогенераторов в Красноярске в официальном сервисном центре PDACENTER.
    Наши инженеры выполняют ремонт любой сложности по дотупным ценам!

  23. JamesGag表示:

    Mexican Pharm International: mexican pharmacy online store – mexican pharmacy online store

  24. LonnieRopay表示:

    Выведи свой Telegram-канал и сайт в ТОП Яндекса!
    Устали от того, что ваш Telegram-канал и сайт теряются в океане информации? Хотите, чтобы ваши клиенты находили вас первыми?

    Мы знаем, как это сделать!

    Наша команда экспертов предлагает профессиональное SEO-продвижение для вашего Telegram-канала и сайта в поисковой выдаче Яндекса.

    Что мы предлагаем:

    Для Telegram-каналов:

    Оптимизация названия и описания: Сделаем ваш канал максимально релевантным поисковым запросам.
    Подбор ключевых слов: Выявим самые эффективные запросы, по которым вас будут искать ваши клиенты.
    Анализ конкурентов: Изучим, как продвигаются ваши конкуренты, и предложим более эффективную стратегию.
    Повышение вовлеченности: Разработаем контент-стратегию для удержания и расширения аудитории (бонусом к SEO!).
    Для сайтов:

    Комплексный SEO-аудит: Выявим все слабые места вашего сайта и предложим решения.
    Внутренняя и внешняя оптимизация: Настроим структуру сайта, контент и ссылочный профиль для лучшего ранжирования.
    Работа с семантическим ядром: Подберем ключевые слова с учетом вашей целевой аудитории и конкуренции.
    Мониторинг и аналитика: Будем отслеживать результаты и вносить коррективы для достижения максимальной эффективности.
    Почему стоит выбрать нас?

    Опыт и экспертиза: Мы успешно продвигаем Telegram-каналы и сайты в Яндексе уже много лет.
    Индивидуальный подход: Разрабатываем стратегию продвижения под конкретные задачи и цели вашего бизнеса.
    Прозрачная отчетность: Предоставляем подробные отчеты о проделанной работе и достигнутых результатах.
    Доступные цены: Предлагаем гибкие тарифные планы, подходящие для любого бюджета.
    Не упустите возможность привлечь новых клиентов и увеличить свою прибыль!

    Закажите бесплатную консультацию прямо сейчас!

    Подписывайтесь на наш канал https://t.me/s/Prodvijenie_telegram_yandex и узнавайте больше о SEO-продвижении!

  25. JamesGag表示:

    mexican pharmacy online order: buying from online mexican pharmacy – reliable mexican pharmacies

發佈留言

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