1. 程式人生 > 實用技巧 >隱祕的物理粒子系統與渲染 !Cocos Creator LiquidFun !

隱祕的物理粒子系統與渲染 !Cocos Creator LiquidFun !

cocos Q彈起來!物理流體之 LiquidFun 流體紋理 shader !

效果預覽

視訊預覽

原理

物理粒子系統

引擎內建的 box2d.js 其實已經攜帶了 googleliquidfun(但是沒有公開介面和適配)。並且引擎還對 box2d 做了一次適配,繫結到全域性變數的 b2

參考 https://github.com/google/liquidfun 中的其中一個demo。

粒子系統建立過程大概分為以下幾步

  • 建立粒子系統定義 ParticleSystemDef (粒子半徑,強度等引數)
  • 通過粒子定義建立粒子系統
  • 建立粒子分組定義 ParticleGroupDef (建立形狀,粒子型別,位置等)
  • 通過粒子分組定義建立粒子分組

需要注意物理世界與引擎內的有一個畫素轉換的關係,轉成 Cocos Creator 中的程式碼大概如下。

const phyMgr = cc.director.getPhysicsManager();
const world = phyMgr['_world'];
const psd = new b2.ParticleSystemDef();
psd.radius = PSD_RADIUS / PTM_RATIO; //每個粒子的半徑
psd.elasticStrength = 0.5;
particleSystem = world.CreateParticleSystem(psd);

const box = new b2.PolygonShape();
const pgd = new b2.ParticleGroupDef();
box.SetAsBox(this.meshRenderer.node.width / 2 / PTM_RATIO, this.meshRenderer.node.height / 2 / PTM_RATIO);
pgd.flags = b2.ParticleFlag.b2_elasticParticle;
pgd.groupFlags = b2.ParticleGroupFlag.b2_solidParticleGroup;
pgd.shape = box;
const particleGroup = particleSystem.CreateParticleGroup(pgd);

渲染

本次採用 cc.MeshRenderer 這個元件去組織頂點紋理資料。並且使用 gl.POINTS 點渲染模式去渲染每個粒子。

主要思路如下:

  • 根據節點位置建立粒子組的位置
  • 建立粒子組後,計算相應的紋理座標
  • 每幀根據物理粒子的位置,更新粒子的頂點座標

如何把物理世界的位置同步到 Cocos 中的位置?

參考引擎原始碼的同步方法,大概也能寫出這個。

const x = posBuff[i].x * PTM_RATIO;
const y = posBuff[i].y * PTM_RATIO;
const pt = this.meshRenderer.node.convertToNodeSpaceAR(cc.v2(x, y));

紋理座標計算這邊寫的比較簡單,沒有考慮節點各種變換和裁剪。(可以參考這篇文章中的紋理計算)

/**
*    t
* l     r
*    b
*/
const u = this._lerp(uv_l, uv_r, (pt.x + texture.width / 2) / texture.width);
const v = this._lerp(uv_b, uv_t, (pt.y + texture.height / 2) / texture.height);

其他

簡單搬運 liquidfun demo,未測試效能,僅供參考學習。專案程式碼在 2.4.x 目錄下。

小結

box2d + LiquidFunParticleSystemshader

以上為白玉無冰使用 Cocos Creator v2.4 實現 "流體之 LiquidFun 流體紋理 shader" 的技術分享。希望這篇 Cocos Creator教程 對你有幫助。

知識不過是潛在的力量,只有將它組織成明確的行動計劃,並指引它朝著某個明確目的發揮作用的時候,知識才是力量。

更多精彩

█ 原創文章導航 █


原文連結