1.x使用shader与2.x使用shader有所不同,2.x的使用例子很多,1.x少些,这里列出使用流光shader例子。
module.exports =
`
attribute vec4 a_position;
attribute vec2 a_texCoord;
attribute vec4 a_color;
varying vec2 v_texCoord;
varying vec4 v_fragmentColor;
void main()
{
gl_Position = CC_PMatrix * a_position;
v_fragmentColor = a_color;
v_texCoord = a_texCoord;
}
`
module.exports =
`
#ifdef GL_ES
precision mediump float;
#endif
varying vec2 v_texCoord;
uniform float sys_time;
void main()
{
vec4 src_color = texture2D(CC_Texture0, v_texCoord).rgba;
float width = 0.2;
float start = sys_time * 1.2;
float strength = 0.02;
float offset = 0.2;
if( v_texCoord.x < (start - offset * v_texCoord.y) && v_texCoord.x > (start - offset * v_texCoord.y - width))
{
vec3 improve = strength * vec3(255, 255, 255);
vec3 result = improve * vec3( src_color.r, src_color.g, src_color.b);
gl_FragColor = vec4(result, src_color.a);
} else {
gl_FragColor = src_color;
}
}
`
// ShaderUtils.js var ShaderUtils = { shaderPrograms: {}, setShader: function(sprite, shaderName) { var glProgram = this.shaderPrograms[shaderName]; if (!glProgram) { glProgram = new cc.GLProgram(); var vert = require(cc.js.formatStr("%s.vert", shaderName)); var frag = require(cc.js.formatStr("%s.frag", shaderName)); glProgram.initWithString(vert, frag); if (!cc.sys.isNative) { glProgram.initWithVertexShaderByteArray(vert, frag); glProgram.addAttribute(cc.macro.ATTRIBUTE_NAME_POSITION, cc.macro.VERTEX_ATTRIB_POSITION); glProgram.addAttribute(cc.macro.ATTRIBUTE_NAME_COLOR, cc.macro.VERTEX_ATTRIB_COLOR); glProgram.addAttribute(cc.macro.ATTRIBUTE_NAME_TEX_COORD, cc.macro.VERTEX_ATTRIB_TEX_COORDS); } glProgram.link(); glProgram.updateUniforms(); this.shaderPrograms[shaderName] = glProgram; } sprite._sgNode.setShaderProgram(glProgram); return glProgram; }, }; module.exports = ShaderUtils;
var ShaderUtils = require("ShaderUtils");
cc.Class({
extends: cc.Component,
properties: {
sp: cc.Sprite,
},
onLoad : function(){
this._time = 0;
this._sin = 0;
this._program = ShaderUtils.setShader(this.sp, "Fluxay");
},
update (dt) {
this._time += 2 * dt;
this._program.use();
this._sin = Math.sin(this._time);
if(this._sin > 0.99){
this._sin = 0;
this._time = 0;
}
if(cc.sys.isNative){
var glProgram_state = cc.GLProgramState.getOrCreateWithGLProgram(this._program);
glProgram_state.setUniformFloat("sys_time", this._sin);
} else {
this._program.setUniformLocationWith1f(this._program.getUniformLocationForName("sys_time"), this._sin);
}
},
});