Cocos2d-js中使用Shader方法

以一个简单的波纹效果为例:

一、引入shader脚本文件。

1、vertex shader

attribute vec4 a_position;
attribute vec2 a_texCoord;
attribute vec4 a_color;

varying vec4 v_fragmentColor;
varying vec2 v_texCoord;

void main()
{
    gl_Position = CC_PMatrix * a_position;
    v_fragmentColor = a_color;
    v_texCoord = a_texCoord;
}

2、fragment shader

varying vec2 v_texCoord;

#define M_PI 3.1415926535897932384626433832795

void main() {
    vec2 coord = v_texCoord;
    coord.x += (sin(coord.y * 10.0 + CC_Time[1] * 10.0) / 30.0);
    gl_FragColor = texture2D(CC_Texture0, coord);
}

3、cocos2d-js code

var sprite = this.sprite = new cc.Sprite("res/demo.png");
sprite.attr({
        x: cc.winSize.width / 2,
        y: cc.winSize.height/ 2
});
this.addChild(sprite);

var shader = this.shader = new cc.GLProgram('res/test.vsh', 'res/test.fsh');
shader.link();
shader.updateUniforms();
        
sprite.shaderProgram = shader;

 

二、直接嵌入shader脚本

      var vsh = "\n" +
            "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()\n" +
            "\n{\n" +
            "   gl_Position = CC_PMatrix * a_position;\n" +
            "   v_fragmentColor = a_color;\n" +
            "   v_texCoord = a_texCoord;\n" +
            "}";

       var fsh = "\n" +
            "varying vec2 v_texCoord;\n" +
            "void main()\n" +
            "\n{\n" +
            "   vec2 coord = v_texCoord;\n" +
            "   coord.x += (sin(coord.y * 10.0 + CC_Time[1] * 10.0) / 30.0);\n" +
            "   gl_FragColor = texture2D(CC_Texture0, coord);\n" +
            "}";

        var sprite = this.sprite = new cc.Sprite("res/grossini.png");
        var shader = new cc.GLProgram();
        if(shader.initWithString(vsh, fsh)){
            shader.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
            shader.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
            shader.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
            shader.link();
            shader.updateUniforms();

            sprite.shaderProgram = shader;
        }
        sprite.attr({
            x: cc.winSize.width / 2,
            y: cc.winSize.height/ 2
        });
        this.addChild(sprite);

 

你可能感兴趣的:(Cocos2d-js中使用Shader方法)