流光效果
原理:在以图片左下角为原点的坐标系中, 假设流光就是一条直线(斜截式:y=kx+b),那么只需要把直线和图片所在矩形的交点全部找出来即可。
顶点着色器代码不用修改。
片元着色器代码如下:
-
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 k; //斜率k
-
float b; //y轴截距b
-
};
-
void main () {
-
vec4 o = vec4(1, 1, 1, 1);
-
//流光宽度
-
float flickerWidth = 0.1;
-
#if USE_TEXTURE
-
o *= texture(texture, v_uv0);
-
//直线斜截式: y = kx + b
-
float y = k*v_uv0.x + b;
-
//转换y轴坐标
-
float y1 = 1.0 - v_uv0.y;
-
if(y1 >= y && y1 <= y + flickerWidth){
-
vec3 white = vec3(255, 255, 255);
-
vec3 result = white * vec3(o.r, o.g, o.b);
-
o = vec4(result, o.a);
-
}
-
#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;
-
}
-
}%
由于流光效果是一个动态的,所以我们要不断改变输入参数b,来实现让流光在图片上移动的效果。
脚本代码如下:
-
const {ccclass, property} = cc._decorator;
-
@ccclass
-
export default class Cocos extends cc.Component {
-
material: cc.Material = null;
-
b:number = 1.0;
-
bMax: number = 1.0;
-
bMin: number = -1.0;
-
start () {
-
//获取材质
-
this.material = this.node.getComponent(cc.Sprite).getMaterial(0);
-
//设置参数k
-
this.material.setProperty("k", 1);
-
}
-
update (dt) {
-
if(this.node.active && this.material != null){
-
//设置参数b
-
this.material.setProperty("b", this.b);
-
}
-
this.b -= 0.03;
-
if(this.b < this.bMin)this.b = this.bMax;
-
}
-
}
-
实际效果图: