Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Unity 插件 MeshEditor(五):不用 3D 軟件也能 K 出網格頂點動畫

編輯:關於 Android 程式設計

這次加入的功能實用性比之前幾個明顯高一些。像破碎、融化那類效果,仔細想想其實沒什麼實際用處——模型的頂點數據本來就該交給 GPU 去繪製,用 CPU 逐幀刷新頂點始終是吃力不討好的事。所以今天要講的網格頂點動畫,也別拿太複雜的模型去試,不然到頭來買單的還是你的項目。

不過簡單模型完全不用擔心。比如旗幟飄揚這種效果:不需要打開 3D 建模軟件去 K 動畫(前提是你就會用那東西),也不受 Unity Animator 系統的格式限制——畢竟給你一個形狀像旗幟的 Cube,你很難用 Animator 調出一段飄動。而這個插件只需要幾步拖拽就能 K 出一段動畫,還能把動畫信息保存成本地文件跨項目復用,甚至頂點數量相同的模型也能共用同一份動畫。

它和 Animator 是兩套東西

網格頂點動畫和 Unity Animator 的機制完全不同,事實上沒有任何關聯,所以兩種動畫可以共存於同一個物體上。原因很簡單:Animator 的關鍵幀只記錄 Transform 組件的 position、rotation、scale,其他屬性變化它一概視而不見;而網格頂點動畫只記錄模型的頂點數據,完全不碰 Transform。互不干涉。

實作流程:給一個 Cube K 動畫

第一步:掛上編輯器組件

為 Cube 添加 MeshAnimation 組件。

「添加動畫幀」的作用是把場景中當前物體的狀態保存為一個新的關鍵幀,代碼上就是記錄每個頂點的位置:

/// <summary>
/// 添加動畫幀
/// </summary>
public void AddFrame() {
    Vector3[] vertices = new Vector3[_Vertices.Length];
    for (int i = 0; i < _Vertices.Length; i++) {
        vertices[i] = _Vertices[i].transform.position;
    }
    _VerticesAnimationArray.Add(vertices);
}

建議在 Cube 的初始狀態就先添加一幀,這樣播放時動畫會從初始形態開始。

第二步:多加幾個關鍵幀

此時每一幀都還是初始形態,先不管。

第三步:調整並應用第二幀

第一幀保持初始狀態。選中第二幀,在場景中直接拖動 Cube 的頂點,滿意之後點擊 apply 把當前形態寫入這一幀;不想要就點 delete 刪除。

/// <summary>
/// 應用動畫幀:把當前物體的頂點數據寫入選中的關鍵幀
/// </summary>
public void ApplyFrame() {
    if (_NowSelectFrame >= 0 && _NowSelectFrame < _VerticesAnimationArray.Count) {
        for (int i = 0; i < _Vertices.Length; i++) {
            _VerticesAnimationArray[_NowSelectFrame][i] = _Vertices[i].transform.position;
        }
    }
}

/// <summary>
/// 刪除動畫幀
/// </summary>
public void DeleteFrame() {
    if (_NowSelectFrame >= 0 && _NowSelectFrame < _VerticesAnimationArray.Count) {
        _VerticesAnimationArray.RemoveAt(_NowSelectFrame);
        _NowSelectFrame = -1;
    }
}

把 Cube 調成下面這個形狀,然後 apply:

第四步~第七步:蓄水、發射、回彈

選中第三幀,再調一個更誇張的形狀並 apply:

第四幀刻意調得和第三幀接近一點,做出緩衝的層次感:

第五幀猛地彈出——前幾幀收縮蓄勢,這一幀瞬間發射,有點發炮彈的意思。這裡有個小技巧:想複製某一幀時,選中它再點添加關鍵幀,末尾就會多出一幀完全相同的副本,在它的基礎上改下一幀會方便很多。

之後再 K 幾個回彈的緩衝幀。這裡要注意交互方式(仿 Animator 的習慣):選中任意一幀,場景中的物體就會立刻變形到那一幀的形態;改動之後必須點擊 apply 才會保存,不點就當無效。

/// <summary>
/// 選定指定幀:把該幀的頂點數據套用到物體上
/// </summary>
public void SelectFrame(int frameIndex) {
    if (frameIndex >= 0 && frameIndex < _VerticesAnimationArray.Count) {
        _NowSelectFrame = frameIndex;
        for (int i = 0; i < _Vertices.Length; i++) {
            _Vertices[i].transform.position = _VerticesAnimationArray[frameIndex][i];
        }
    }
}

完成後點擊預覽按鈕,就能在 Scene 視圖裡直接看到動畫效果。

這裡有個技術細節:即使腳本加了 ExecuteInEditMode 標識,Update 也不會逐幀執行,只在場景物體發生變化時才觸發。所以動畫預覽不能寫在 Update 裡,必須掛到 Unity 編輯器的幀刷新週期上。

/// <summary>
/// 開始預覽動畫
/// </summary>
public void PlayAnimation() {
    if (_VerticesAnimationArray.Count <= 0) return;

    _AnimationIndex = 0;          // 從第一幀開始
    _AnimationLastIndex = -1;     // 重置上一序列記錄
    _AnimationFragment = new Vector3[_Vertices.Length];
    _AnimationPlayControl = 0;    // 重置播放控制器

    for (int i = 0; i < _Vertices.Length; i++) {
        _Vertices[i].transform.position = _VerticesAnimationArray[0][i];
    }

    _IsPlay = true;
    // 註冊到編輯器的逐幀刷新週期
    EditorApplication.update += PlayingAnimation;
}

刷新函數的思路是「把每一幀切分成動畫片段,再逐幀累加」:

/// <summary>
/// 動畫預覽中
/// </summary>
void PlayingAnimation() {
    if (!_IsPlay) return;

    // 播放到最後一幀,收尾
    if (_AnimationIndex + 1 >= _VerticesAnimationArray.Count) {
        _IsPlay = false;
        EditorApplication.update -= PlayingAnimation;
        for (int i = 0; i < _Vertices.Length; i++) {
            _Vertices[i].transform.position = _VerticesAnimationArray[0][i];
        }
        return;
    }

    // 進入新的一幀時,重新切分動畫片段
    if (_AnimationIndex != _AnimationLastIndex) {
        _AnimationLastIndex = _AnimationIndex;
        for (int i = 0; i < _AnimationFragment.Length; i++) {
            _AnimationFragment[i] = (_VerticesAnimationArray[_AnimationIndex + 1][i]
                    - _VerticesAnimationArray[_AnimationIndex][i]) / _AnimationPlaySpeed;
        }
    }

    for (int i = 0; i < _Vertices.Length; i++) {
        _Vertices[i].transform.position += _AnimationFragment[i];
    }

    _AnimationPlayControl += 1;
    if (_AnimationPlayControl >= _AnimationPlaySpeed) {
        _AnimationPlayControl = 0;
        _AnimationIndex += 1;
    }
    RefishMesh();
}

第八步:記得先導出動畫(重點)

千萬別忘記點擊「導出動畫」。如果你直接點「編輯完成」,或者中途突然想到什麼好主意跑去 VS 改腳本導致 Unity 重新編譯,那麼剛才 K 的動畫數據會全部丟失。正確順序是:先導出,再編輯完成。

這裡用 ScriptableObject 把動畫數據序列化到 asset 文件。有兩個必須遵守的約定,否則會踩坑:路徑必須以 Assets/ 開頭,後綴必須是 .asset。

/// <summary>
/// 導出動畫
/// </summary>
public void ExportAnimation() {
    if (_VerticesAnimationArray.Count <= 1) return;

    MeshAnimationAsset meshAnimationAsset = ScriptableObject.CreateInstance<MeshAnimationAsset>();

    meshAnimationAsset._VertexNumber = _RecordAllVerticesList.Count;
    meshAnimationAsset._FrameNumber = _VerticesAnimationArray.Count;
    meshAnimationAsset._VerticesAnimationArray =
            new Vector3[_VerticesAnimationArray.Count * _RecordAllVerticesList.Count];

    for (int n = 0; n < _VerticesAnimationArray.Count; n++) {
        for (int i = 0; i < _VerticesAnimationArray[n].Length; i++) {
            for (int j = 0; j < _AllVerticesGroupList[i].Count; j++) {
                int number = n * _RecordAllVerticesList.Count + _AllVerticesGroupList[i][j];
                EditorUtility.DisplayProgressBar("導出動畫",
                        "正在導出頂點數據(" + number + "/"
                                + meshAnimationAsset._VerticesAnimationArray.Length + ")......",
                        1.0f / meshAnimationAsset._VerticesAnimationArray.Length * number);
                // 世界坐標轉回模型本地坐標
                meshAnimationAsset._VerticesAnimationArray[number] =
                        transform.worldToLocalMatrix.MultiplyPoint3x4(
                                _VerticesAnimationArray[n][i]);
            }
        }
    }

    string path = "Assets/" + GetComponent<MeshFilter>().sharedMesh.name + "AnimationData.asset";
    AssetDatabase.CreateAsset(meshAnimationAsset, path);
    EditorUtility.ClearProgressBar();
}

導出的動畫數據文件裡可以看到 10 個關鍵幀,適用於任何具有 24 個網格頂點的模型(可操控頂點數量的 3 倍)。

第九步:掛上播放器組件

為 Cube 添加 MeshAnimationPlayer,並指定剛才導出的 CubeAnimationData。一個 MeshAnimationPlayer 對應一個 AnimationData 文件,目前暫不支持在代碼中動態更換。

  • MeshAnimationAsset:播放器要讀取的 asset 文件,頂點數量必須與當前物體一致。
  • AnimationPlaySpeed:播放速度。注意這裡是值越小播放越快。
  • 另外兩個開關分別是循環播放和「啟動時即播放」。

勾選啟動播放,運行程序:

效果確實有點醜,畢竟只是隨手調的形狀,我又不是美術。

播放器的播放/停止也提供了外部可控開關:

/// <summary>
/// 播放動畫
/// </summary>
public void Play() {
    _AnimationIndex = 0;
    _AnimationLastIndex = -1;
    _AnimationPlayControl = 0;
    SelectFrame(_AnimationIndex);
    _IsPlaying = true;
}

/// <summary>
/// 停止播放
/// </summary>
public void Stop() {
    _IsPlaying = false;
    SelectFrame(0);   // 回歸第一幀
}

想知道當前是否正在播放,直接讀取 _IsPlaying 屬性即可。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved