LibGDX 游戲開發 之 2D動畫

原文鏈接:https://github.com/libgdx/libgdx/wiki/2D-Animation
譯者:重慶好爸爸 game4kids@163.com
謝絕轉載

概述

2D動畫是一種使用靜態圖片來創建動態效果的技術。這篇文章描述了如何利用libGDX的Animation類來創建動畫。
動畫是由按照設置的時間間隔和和一定順序顯示的多個幀。比如可以通過拍攝人跑步時的多張照片,然后在循環播放這些照片來實現這個人跑步的動畫。
下面的“sprite sheet”圖展示了一個人跑步的完整周期。每個框包含一個靜態畫面。當這些畫面在一段時間內順序顯示時,它們將形成動畫。

幀率表示每秒顯示的畫面數量。上面的例子中,整個跑步周期共有30幀畫面。如果角色在1秒中內完成整個跑步周期,那么這30幀畫面需要在1秒鐘之內全部顯示完,這中情況下幀率就是 30 FPS。每幀的時間(稱為幀時間或間隔時間)是FPS的倒數,在這種情況下為每幀0.033秒

animation是一個非常簡單的狀態機。在例子中跑步的人一共有30個狀態。編號的幀表示跑步的人經歷的狀態,一個時間只能存在一個狀態。當前是何種狀態取決于動畫開始后到當前經歷的時間。如果少于0.033秒,我們在狀態1,所以第一個sprite被繪制。 如果我們在0.033和0.067秒之間,那么我們在狀態2,依此類推。 如果動畫循環,則在顯示所有幀后返回到第一幀。


Animation類 The Animation class

LibGDX's Animation (code) 類可以用來方便的管理動畫。Animation類通過一系列圖片和幀間隔來創建動畫。在動畫播放的時候,getKeyFrame()方法可以通過一個elapsed time參數得到相應的圖像。
Animation有一個泛型參數,用來表示圖像的類型。 典型的類型是TextureRegion 或者 PolygonRegion, 但是任何renderable 對象都是可以的。該類型通過在動畫聲明中,指定動畫類型來聲明,比如:

Animation<TextureRegion> myAnimation = new Animation<TextureRegion>(/*...*/)

請注意,使用Sprite類來表示動畫的幀通常是不合適的,因為Sprite類包含的位置數據不是從幀到幀的(because the Sprite class contains positional data that would not carry from frame to frame.)。

TextureAtlas 例子

LibGDX's TextureAtlas (code)
通常用于將許多單獨的紋理區域組合成較小的紋理集合,以減少昂貴的繪圖調用 (details here).
TexturePacker和TextureAtlas提供了一種方便的方法來生成動畫。 動畫的所有源圖像應以最后的下劃線和幀號命名,如running_0.png, running_1.png, running_2.png, etc. TexturePacker 會自動使用這些號碼來作為幀的編號(要求打包參數: use-Indexes 為 true)。
加載TextureAtlas之后,可以立即獲取完整的幀數組,并將其傳遞到Animation構造函數中:

public Animation<TextureRegion> runningAnimation;
//...
runningAnimation = new Animation<TextureRegion>(0.033f, atlas.findRegions("running"), PlayMode.LOOP);

Sprite sheet example

以下代碼片段將使用animation_sheet.png sprite-sheet創建一個動畫,并將動畫渲染到屏幕。

public class Animator implements ApplicationListener {

    // Constant rows and columns of the sprite sheet
    private static final int FRAME_COLS = 6, FRAME_ROWS = 5;

    // Objects used
    Animation<TextureRegion> walkAnimation; // Must declare frame type (TextureRegion)
    Texture walkSheet;
    SpriteBatch spriteBatch;

    // A variable for tracking elapsed time for the animation
    float stateTime;

    @Override
    public void create() {

        // Load the sprite sheet as a Texture
        walkSheet = new Texture(Gdx.files.internal("animation_sheet.png"));

        // Use the split utility method to create a 2D array of TextureRegions. This is 
        // possible because this sprite sheet contains frames of equal size and they are 
        // all aligned.
        TextureRegion[][] tmp = TextureRegion.split(walkSheet, 
                walkSheet.getWidth() / FRAME_COLS,
                walkSheet.getHeight() / FRAME_ROWS);

        // Place the regions into a 1D array in the correct order, starting from the top 
        // left, going across first. The Animation constructor requires a 1D array.
        TextureRegion[] walkFrames = new TextureRegion[FRAME_COLS * FRAME_ROWS];
        int index = 0;
        for (int i = 0; i < FRAME_ROWS; i++) {
            for (int j = 0; j < FRAME_COLS; j++) {
                walkFrames[index++] = tmp[i][j];
            }
        }

        // Initialize the Animation with the frame interval and array of frames
        walkAnimation = new Animation<TextureRegion>(0.025f, walkFrames);

        // Instantiate a SpriteBatch for drawing and reset the elapsed animation
        // time to 0
        spriteBatch = new SpriteBatch();
        stateTime = 0f;
    }

    @Override
    public void render() {
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); // Clear screen
        stateTime += Gdx.graphics.getDeltaTime(); // Accumulate elapsed animation time
        
        // Get current frame of animation for the current stateTime
        TextureRegion currentFrame = walkAnimation.getKeyFrame(stateTime, true);
        spriteBatch.begin();
        spriteBatch.draw(currentFrame, 50, 50); // Draw current frame at (50, 50)
        spriteBatch.end();
    }

    @Override
    public void dispose() { // SpriteBatches and Textures must always be disposed
        spriteBatch.dispose();
        walkSheet.dispose();
    }
}

使用以下構造函數創建動畫非常簡單。

Method signature Description
Animation (float frameDuration, TextureRegion... keyFrames) The first parameter is the frame time and the second is an array of regions (frames) making up the animation

Best practices

  • 將幀與其他sprites一起打包成一個紋理,可以優化渲染。 這很容易用TexturePacker完成。
  • 根據游戲類型確定合理數量的幀。 對于復古的街機風格,10 fps可能就足夠了,而更逼真的運動需要更多的幀。

Asset

獲取 sprite-sheet 這里.

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,461評論 6 532
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,538評論 3 417
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,423評論 0 375
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,991評論 1 312
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,761評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,207評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,268評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,419評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,959評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,782評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,983評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,528評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,222評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,653評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,901評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,678評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,978評論 2 374

推薦閱讀更多精彩內容