花草擺動效果
原理:根據時間的推移計算出x軸方向上的偏移量,然後把紋理中的每個點的顏色修改成發生偏移之後點的顏色。
先放一張靜止狀態的畫草圖
頂點着色器代碼不用修改。
片元着色器代碼如下:
CCProgram fs %{
precision highp float;
#include <alpha-test>
in vec4 v_color;
#if USE_TEXTURE
in vec2 v_uv0;
uniform sampler2D texture;
#endif
uniform inputData{
float time;
};
void main () {
vec4 o = vec4(1, 1, 1, 1);
//獲取v_uv0這個點的高度
float height = 1.0 - v_uv0.y;
//使用pow函數,讓越高的地方擺動幅度越明顯且成拋物線形態
float k = 0.1*pow(height, 2.0);
//x軸偏移量,使用sin函數實現兩邊擺動效果,time*2.0是爲了加快擺動
float offset = k*sin(time*2.0);
#if USE_TEXTURE
//fract函數是GLSL內建函數,取小數部分
o *= texture(texture, fract(vec2(v_uv0.x + offset, v_uv0.y)));
#if CC_USE_ALPHA_ATLAS_TEXTURE
o.a *= texture2D(texture, v_uv0 + vec2(0, 0.5)).r;
#endif
#endif
o *= v_color;
ALPHA_TEST(o);
gl_FragColor = o;
}
}%
腳本代碼:
const {ccclass, property} = cc._decorator;
@ccclass
export default class Grass extends cc.Component {
material: cc.Material = null;
time: number = 0;
start () {
this.material = this.node.getComponent(cc.Sprite).getMaterial(0);
//this.material.define();
}
update (dt) {
this.time += dt;
if(this.node.active && this.material != null){
this.material.setProperty("time", this.time);
}
}
}
效果圖如下:
花朵在搖擺的時候有點變形,效果勉強過得去吧!