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

有小伙伴提出了这个问题,其实GLProgramCocos2d-x引擎自带了。完全可以直接拿来用。

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

【玩转cocos2d-x之四十】如何在Cocos2d-x 3.0中使用opengl shader?_第1张图片【玩转cocos2d-x之四十】如何在Cocos2d-x 3.0中使用opengl shader?_第2张图片

1.在cpp中使用openGL shader。

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

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);
    }
}

2.在js中使用opengl shader.

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

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();//cc.GLProgram.create("gray.vsh", "gray.fsh");
        shader.retain();
        //shader.initWithByteArrays("res/gray.vsh", "res/gray.fsh");
        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
翻译自:
1. http://www.cocos2d-x.org/forums/6/topics/49035
2. http://www.cocos2d-x.org/forums/19/topics/49038

你可能感兴趣的:(cocos2d-x)