Shader Script:
# ifdef GL_ES
precision mediump float;
# endif
uniform sampler2D u_texture;
varying vec2 v_texCoord;
varying vec4 v_fragmentColor;
void main(void)
{
// Convert to greyscale using NTSC weightings
float alpha = texture2D(u_texture, v_texCoord).a;
float grey = dot(texture2D(u_texture, v_texCoord).rgb, vec3(0.299, 0.587, 0.114));
gl_FragColor = vec4(grey, grey, grey, alpha);
}
Use the shader script in CCSprite:
//Create shader
CCGLProgram *shader = new CCGLProgram();
shader->initWithVertexShaderByteArray(ccPositionTextureA8Color_vert, shader_frag_grayscale);
shader->addAttribute(kCCAttributeNamePosition, kCCVertexAttrib_Position);
shader->addAttribute(kCCAttributeNameColor, kCCVertexAttrib_Color);
shader->addAttribute(kCCAttributeNameTexCoord, kCCVertexAttrib_TexCoords);
shader->link();
shader->updateUniforms();
//Setup shader program to sprite
sprite->setShaderProgram(shader);
shader_frag_grayscale
is the content of the shader script.
Update:
If you want to change the alpha of the sprite, you should set the blend mode in CCSprite to this:
m_sBlendFunc.src = GL_SRC_ALPHA;
m_sBlendFunc.dst = GL_ONE_MINUS_SRC_ALPHA;
Then if you change the alpha
here will work.
gl_FragColor = vec4(grey, grey, grey, alpha);
参考:
グレースケールのアニメーション表示をしてみる
Cocos2d-x 2.x CCSprite 灰白图的生成(利用shader设置)