【玩转cocos2d-x之四十】如何在Cocos2d-x 3.0中使用opengl shader?

前端之家收集整理的这篇文章主要介绍了【玩转cocos2d-x之四十】如何在Cocos2d-x 3.0中使用opengl shader?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有小伙伴提出了这个问题,其实GLProgramCocos2d-x引擎自带了。完全可以直接拿来用。

先上图吧。使用opengl前后的对比:


1.在cpp中使用openGL shader。

(1)添加gray.vsh和gray.fsh到资源目录(见附件)。
(2)添加如下代码

  1. boolHelloWorld::init()
  2. {
  3. if(!Layer::init())
  4. returnfalse;
  5. }
  6. izevisibleSize=Director::getInstance()->getVisibleSize();
  7. autosprite=Sprite::create("HelloWorld.png");
  8. sprite->setAnchorPoint(Point(0.5,0.5));
  9. sprite->setPosition(Point(visibleSize.width/3,visibleSize.height/3));
  10. this->addChild(sprite);
  11. graySprite(sprite);
  12. true;
  13. voidHelloWorld::graySprite(Sprite*sprite)
  14. {
  15. if(sprite)
  16. GLProgram*p=newGLProgram();
  17. p->initWithFilenames("gray.vsh","gray.fsh");
  18. p->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_POSITION,GLProgram::VERTEX_ATTRIB_POSITION);
  19. p->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_COLOR,GLProgram::VERTEX_ATTRIB_COLOR);
  20. p->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_TEX_COORD,GLProgram::VERTEX_ATTRIB_TEX_COORDS);
  21. p->link();
  22. p->updateUniforms();
  23. sprite->setShaderProgram(p);
  24. }

2.在js中使用opengl shader.

(1)添加gray.vsh和gray.fsh到资源目录。
(2)添加如下代码

[javascript]
    varHelloWorldLayer=cc.Layer.extend({
  1. sprite:null,
  2. ctor:function()
  3. this._super();
  4. varsize=cc.director.getWinSize();
  5. this.sprite=cc.Sprite.create(res.HelloWorld_png);
  6. this.sprite.attr({
  7. x:size.width/2,
  8. y:size.height/2,
  9. scale:0.5,248)"> rotation:180
  10. });
  11. this.addChild(this.sprite,0);
  12. graySprite(this.sprite);
  13. true;
  14. }
  15. });
  16. functiongraySprite(sprite)
  17. varshader=newcc.GLProgram();//cc.GLProgram.create("gray.vsh","gray.fsh");
  18. shader.retain();
  19. //shader.initWithByteArrays("res/gray.vsh","res/gray.fsh");
  20. shader.initWithFilenames("res/gray.vsh","res/gray.fsh");
  21. shader.addAttribute(cc.ATTRIBUTE_NAME_POSITION,cc.VERTEX_ATTRIB_POSITION);
  22. shader.addAttribute(cc.ATTRIBUTE_NAME_COLOR,cc.VERTEX_ATTRIB_COLOR);
  23. shader.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD,cc.VERTEX_ATTRIB_TEX_COORDS);
  24. shader.link();
  25. shader.updateUniforms();
  26. sprite.setShaderProgram(shader);
  27. }

附件:gray.vsh和gray.fsh
翻译自:
1. http://www.cocos2d-x.org/forums/6/topics/49035
2. http://www.cocos2d-x.org/forums/19/topics/49038

猜你在找的Cocos2d-x相关文章