我从cocos2dx 3.x开始研究的,发现网上有很多在2.x变灰的例子,甚至需要改源码,而我个人偏向于静态方法的封装的用法,所以整合总结并测试了如下方法。在cocos2dx 3.4版本通过,关于偏移问题确实恶心,查阅很多博文已解决,有了这个方法我就准备在下一篇实现一个技能CD效果的通用方案。
static void SwitchGray (Sprite *sp, bool isGray) { GLchar* grayvsh = "attribute vec4 a_position; \n \ attribute vec2 a_texCoord; \n \ attribute vec4 a_color; \n \ varying vec4 v_fragmentColor;\n \ varying vec2 v_texCoord;\n \ void main(void) \n \ { \n \ gl_Position = CC_PMatrix * a_position;\n \ v_fragmentColor = a_color;\n \ v_texCoord = a_texCoord;\n \ }"; if(isGray) { GLchar* grayfsh= "varying vec4 v_fragmentColor;\n \ varying vec2 v_texCoord;\n \ void main()\n \ {\n \ vec4 v_orColor = v_fragmentColor * texture2D(CC_Texture0, v_texCoord);\n \ float gray = dot(v_orColor.rgb, vec3(0.299, 0.587, 0.114));\n \ gl_FragColor = vec4(gray, gray, gray, v_orColor.a);\n \ }"; GLProgram* pProgram = new GLProgram(); pProgram->initWithVertexShaderByteArray(grayvsh, grayfsh); sp->setShaderProgram(pProgram); pProgram->release(); CHECK_GL_ERROR_DEBUG(); } else { GLProgram* pProgram = new GLProgram(); //pProgram->initWithFilenames("gray.vsh", "color.fsh"); pProgram->initWithVertexShaderByteArray(grayvsh, ccPositionTextureColor_frag); sp->setShaderProgram(pProgram); pProgram->release(); CHECK_GL_ERROR_DEBUG(); } sp->getShaderProgram()->addAttribute(GLProgram::ATTRIBUTE_NAME_POSITION,kCCVertexAttribFlag_Position); sp->getShaderProgram()->addAttribute(GLProgram::ATTRIBUTE_NAME_POSITION, kCCVertexAttrib_Position); sp->getShaderProgram()->addAttribute(GLProgram::ATTRIBUTE_NAME_COLOR, kCCVertexAttrib_Color); sp->getShaderProgram()->addAttribute(GLProgram::ATTRIBUTE_NAME_TEX_COORD, kCCVertexAttrib_TexCoords); CHECK_GL_ERROR_DEBUG(); sp->getShaderProgram()->link(); CHECK_GL_ERROR_DEBUG(); sp->getShaderProgram()->updateUniforms(); CHECK_GL_ERROR_DEBUG(); }