【玩转cocos2d-x之四十一】在Cocos2d-x 3.0中使用opengl shader
有小伙伴提出了这个问题,其实GLProgram Cocos2d-x引擎自带了。完全可以直接拿来用。
先上图吧。使用opengl前后的对比:
在cpp中使用openGL shader
- 添加gray.vsh和gray.fsh到资源目录(见附件)。
- 添加如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| bool HelloWorld::init() { if ( !Layer::init() ) { return false; } ize visibleSize = Director::getInstance()->getVisibleSize(); auto sprite = Sprite::create("HelloWorld.png"); sprite->setAnchorPoint(Point(0.5, 0.5)); sprite->setPosition(Point(visibleSize.width / 3, visibleSize.height / 3)); this->addChild(sprite); graySprite(sprite); return true; } void HelloWorld::graySprite(Sprite * sprite) { if(sprite) { GLProgram * p = new GLProgram(); p->initWithFilenames("gray.vsh", "gray.fsh"); p->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_POSITION, GLProgram::VERTEX_ATTRIB_POSITION); p->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_COLOR, GLProgram::VERTEX_ATTRIB_COLOR); p->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_TEX_COORD, GLProgram::VERTEX_ATTRIB_TEX_COORDS); p->link(); p->updateUniforms(); sprite->setShaderProgram(p); } }
|
在js中使用opengl shader
- 添加gray.vsh和gray.fsh到资源目录。
- 添加如下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| var HelloWorldLayer = cc.Layer.extend({ sprite:null, ctor:function () { this._super(); var size = cc.director.getWinSize(); this.sprite = cc.Sprite.create(res.HelloWorld_png); this.sprite.attr({ x: size.width / 2, y: size.height / 2, scale: 0.5, rotation: 180 }); this.addChild(this.sprite, 0); graySprite(this.sprite); return true; } }); function graySprite(sprite) { if(sprite) { var shader = new cc.GLProgram(); shader.retain(); shader.initWithFilenames("res/gray.vsh", "res/gray.fsh"); shader.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); shader.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR); shader.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS); shader.link(); shader.updateUniforms(); sprite.setShaderProgram(shader); } }
|
附件:gray.vsh和gray.fsh
翻译自: