飘扬的旗帜!shader 编程实战!Cocos Creator!

用 shader + mesh 立个 flag 吧! 文章底部获取完整代码!node

效果预览

使用方法

  1. 建立一个空节点
  2. 添加用户脚本组件 mesh-texture-flag
  3. 添加图片
  4. 修改对应属性

实现原理

归纳来讲就是建立 mesh 网格模型,经过顶点着色器对顶点坐标不断的修改,达到飘动的效果。关于 mesh 的介绍,能够参考上一篇文章。git

肯定顶点坐标

为了让顶点着色器里有多个顶点能够改变位置,须要把一个形状分割成多个方形(三角形)。分割数量越大,效果越精细,但须要消耗更多的性能消耗。下图是分割成两行三列的例子。github

根据分割的行列数和节点大小,节点锚点,从左到右从上到下,算出每一个顶点的位置信息。能够先算出相对左上角的位置,而后再根据锚点偏移,参考代码以下。编辑器

const x = (_col - this._col * this.node.anchorX) * _width / this._col;
const y = (_row - this._row * this.node.anchorY) * _height / this._row;

肯定纹理uv坐标

纹理uv坐标系在左上角,u轴是向右,v轴是向下,范围是 0-1。而咱们的坐标系是根据锚点肯定的,x轴向右,y轴向上。函数

根据锚点求出位置坐标在左下角的占比,而后再翻转一下v就能够求出对应的uv坐标了。参考代码以下。性能

const u = (pt.x + this.texture.width * this.node.anchorX + this.offset.x) / this.texture.width;
const v = 1.0 - (pt.y + this.texture.height * this.node.anchorY + this.offset.y) / this.texture.height;

肯定顶点索引

从网格左上角的格子开始,依次肯定三角形顶点画法。下图是分割成两行两列的索引。this

每一个格子有两个三角形,参考代码以下。3d

// 计算顶点索引 
let ids = [];
let getIndexByRowCol = (_row, _col) => {
    return _row * (this._col + 1) + _col;
}
for (let _row = 0; _row < this._row; _row++) {
    for (let _col = 0; _col < this._col; _col++) {
        ids.push(getIndexByRowCol(_row, _col), getIndexByRowCol(_row, _col + 1), getIndexByRowCol(_row + 1, _col));
        ids.push(getIndexByRowCol(_row + 1, _col), getIndexByRowCol(_row + 1, _col + 1), getIndexByRowCol(_row, _col + 1));
    }
};

顶点着色器编写

使用的是sin函数对顶点进行修改。code

一个波浪就是一个 PI , 因此要把位置坐标变化幅度映射到 wave * PI 。经过求出占宽度比就能够获得 sin 函数的角度了。blog

经过内置变量 cc_time 能够使坐标随着时间变化。不过得在非编辑器下才能预览到,由于默认是不会赋值的。

参考代码以下。

float angleSpanH = wave * 3.14159265;
float pz = amplitude * sin(cc_time.x * speed - (a_position.x - startPos.x + a_position.y - startPos.y) / textureWidth * angleSpanH);
vec4 position = vec4(a_position.x, a_position.y + pz, a_position.z, 1);

小结

以上为白玉无冰使用 Cocos Creator v2.2.2 开发 "飘扬的旗帜!" 的技术分享。有想法欢迎留言!若是这篇对你有点帮助,欢迎分享给身边的朋友。


完整代码
原文连接

相关文章
相关标签/搜索