首先须要两个文件
gray.fsh
varying vec4 v_fragmentColor; varying vec2 v_texCoord; void main() { vec4 v_orColor = v_fragmentColor * texture2D(CC_Texture0, v_texCoord); float gray = dot(v_orColor.rgb, vec3(0.299, 0.587, 0.114)); gl_FragColor = vec4(gray, gray, gray, v_orColor.a); }
gray.vsh
attribute vec4 a_position; attribute vec2 a_texCoord; attribute vec4 a_color; varying vec4 v_fragmentColor; varying vec2 v_texCoord; void main() { gl_Position = CC_MVPMatrix * a_position; v_fragmentColor = a_color; v_texCoord = a_texCoord; }
声明函数
void shader(Sprite* sprite);
实现函数
void Nice::shader(Sprite* sprite) { auto glprogram = GLProgram::createWithFilenames("gray.vsh", "gray.fsh"); auto glprogramstate = GLProgramState::getOrCreateWithGLProgram(glprogram); sprite->setGLProgramState(glprogramstate); }
以后要对某个精灵实现这个shader效果就直接shader(sp)就好了
sp_point = Sprite::create("newAlwaysShow.png"); sp_point->setAnchorPoint(Vec2::ZERO); sp_point->setPosition(Vec2(200, 200)); addChild(sp_point); shader(sp_point);