Cocos2d-js中使用Shader方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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方法的主要内容,如果未能解决你的问题,请参考以下文章

Cg入门20:Fragment shader - 片段级模型动态变色(实现汽车动态换漆)

Cg入门17:Fragment shader - 片段级光照(添加阴影)

Shader HLSL片段说明

Cg入门19:Fragment shader - 片段级模型动态变色

如何学习shader

Cg入门16:Fragment shader - 片段级光照