用cocos2d-x 实现UV动画--实现篇

用cocos2d-x 实现UV动画--实现篇,第1张

概述用cocos2d-x 实现UV动画--实现篇 UVSprite uv动画是指通过在程序运行时动态改变纹理坐标,实现动态效果的纹理动画,使用uv动画可以实现水流动,火焰燃烧等效果。 下图是UVSprite实现的一个动画效果 本文由liangneo原创,转载请保留原文地址 :http://blog.csdn.net/liangneo/article/details/42583533 1.分析 我们需要 用cocos2d-x 实现UV动画--实现篇 UVSprite

uv动画是指通过在程序运行时动态改变纹理坐标,实现动态效果的纹理动画,使用uv动画可以实现水流动,火焰燃烧等效果。

下图是UVSprite实现的一个动画效果



本文由liangneo原创,转载请保留原文地址 :http://blog.csdn.net/liangneo/article/details/42583533


1.分析

我们需要的是一个具uv动画的sprite,最简单合理的方式是让你UVSprite直接继承于CCSprite,另外我们还需要两个变量来控制U或V方面是否需要动画,另外两个变量来控制U和V方向的动画速度,因此UVSprite类的声明如下:

class UVSprite : public cocos2d::CCSprite{  //U方向是否需要动画  bool _autoScrollU = true;  //U方面动画速度(0~~1)  float _autoScrollSpeedU =0;  //V方向是否需要动画  bool _autoScrollV = false;  //V方向的动画速度(0~~1)  float _autoScrollSpeedV=0;  //保存当前已经移动的uv值  float _autoScrollCountU=0;  float _autoScrollCountV=0;};
另外我们还需要两个接口来创建UVSprite和CCSprite保持一致:
	//从pList中的frame创建    static UVSprite* createWithSpriteFramename(const char *pszSpriteFramename);    //从贴图文件直接创建    static UVSprite* create(const char *pszfilename);


另外我们还需要一个update来更新uv的偏移值:

voID UVSprite::update(float dt){    CCSprite::update(dt);        //更新u    if(_autoScrollU)    {        _autoScrollCountU += dt * _autoScrollSpeedU;    }        //更新v    if (_autoScrollV) {        _autoScrollCountV += dt * _autoScrollSpeedV;    }        //如果超出范围从0开始    if (_autoScrollCountU > 1 || _autoScrollCountU < -1) {        _autoScrollCountU = 0;    }        if (_autoScrollCountV > 1 || _autoScrollCountV < -1) {        _autoScrollCountV = 0;    }}

上一篇文章中我们提到,uv的值在(0~~1)范围内,因此在更新时确保偏移在(-1,1)范围内


2.shader

a.有了更新uv的更新我们来写shader,顶点shader我们使用cocos2d提供的 ccpositionTexturecolor_vert,代码如下

attribute vec4 a_position;							attribute vec2 a_texCoord;							attribute vec4 a_color;																					#ifdef GL_ES										varying lowp vec4 v_fragmentcolor;					varying mediump vec2 v_texCoord;					#else												varying vec4 v_fragmentcolor;						varying vec2 v_texCoord;							#endif																									voID main()											{													    gl_position = CC_MVPMatrix * a_position;			v_fragmentcolor = a_color;							v_texCoord = a_texCoord;						}						

b.片元shader,在片元shader中我们需要更新uv坐标,设置一个变量texOffset来表示uv的偏移,代码如下:
#ifdef GL_ES								precision lowp float;						#endif										varying vec4 v_fragmentcolor;				varying vec2 v_texCoord;					uniform vec2 texOffset;                 uniform sampler2D CC_Texture0;				voID main()									{												vec2 texcoord = mod(texOffset+v_texCoord,1.0);   	gl_Fragcolor = v_fragmentcolor * texture2D(CC_Texture0,texcoord);			}	

在片元Shader中,我们将默认的v_texCoord加上传进来的texOffset,并对结果与1求模,确保纹理坐标出界后回到合理的位置


3.shader加载,为UVSprite添加一个成员函数,和一个shader中texOffset的uniform引用,代码如下:

voID UVSprite::loadShaderVertex(const char *vert,const char *frag){    CCGLProgram *shader = new CCGLProgram();    shader->initWithVertexShaderByteArray(vert,frag);        shader->addAttribute(kCCAttributenameposition,kCCVertexAttrib_position);    shader->addAttribute(kCCAttributenamecolor,kCCVertexAttrib_color);    shader->addAttribute(kCCAttributenameTexCoord,kCCVertexAttrib_TexCoords);        shader->link();        shader->updateUniforms();        _uniformOffset = glGetUniformlocation(shader->getProgram(),"texOffset");        this->setShaderProgram(shader);        shader->release();}
在该函数中,首先加载sahder,添加cocos2dx提供三个默认属性,分别是点坐标,点颜色,点的uv坐标,然后获取texOffset在shahder中的uniform引用

4.渲染,重写CCSprite的draw函数,除了实现CCSprite的draw的渲染功能,还额外的绑定texOffset,代码如下:

voID UVSprite::draw(){    CC_PROfileR_START_category(kCCProfilercategorySprite,"CCSprite - draw");        CCAssert(!m_pobBatchNode,"If CCSprite is being rendered by CCSpriteBatchNode,CCSprite#draw SHOulD NOT be called");        getShaderProgram()->use();    getShaderProgram()->setUniformsForBuiltins();        ccGLBlendFunc( m_sBlendFunc.src,m_sBlendFunc.dst );    //绑定texOffset    getShaderProgram()->setUniformlocationWith2f(_uniformOffset,_autoScrollCountU,_autoScrollCountV);    //绑定纹理贴图    ccGLBindTexture2D( m_pobTexture->getname() );    ccGLEnabLevertexAttribs( kCCVertexAttribFlag_PoscolorTex );    #define kQuadSize sizeof(m_squad.bl)#ifdef EMSCRIPTEN    long offset = 0;    setGLBufferData(&m_squad,4 * kQuadSize,0);#else    long offset = (long)&m_squad;#endif // EMSCRIPTEN            // 设置渲染坐标(x,y)    int diff = offsetof( ccV3F_C4B_T2F,vertices);    glVertexAttribPointer(kCCVertexAttrib_position,3,GL_float,GL_FALSE,kQuadSize,(voID*) (offset + diff));        // 设置纹理坐标(u,v)    diff = offsetof( ccV3F_C4B_T2F,texCoords);    glVertexAttribPointer(kCCVertexAttrib_TexCoords,2,(voID*)(offset + diff));        // 设置顶点颜色    diff = offsetof( ccV3F_C4B_T2F,colors);    glVertexAttribPointer(kCCVertexAttrib_color,4,GL_UNSIGNED_BYTE,GL_TRUE,(voID*)(offset + diff));        //渲染矩形    glDrawArrays(GL_TRIANGLE_STRIP,4);        CHECK_GL_ERROR_DEBUG();        #if CC_SPRITE_DEBUG_DRAW == 1    // draw bounding Box    CCPoint vertices[4]={        ccp(m_squad.tl.vertices.x,m_squad.tl.vertices.y),ccp(m_squad.bl.vertices.x,m_squad.bl.vertices.y),ccp(m_squad.br.vertices.x,m_squad.br.vertices.y),ccp(m_squad.tr.vertices.x,m_squad.tr.vertices.y),};    ccDrawpoly(vertices,true);#elif CC_SPRITE_DEBUG_DRAW == 2    // draw texture Box    CCSize s = this->getTextureRect().size;    CCPoint offsetPix = this->getoffsetposition();    CCPoint vertices[4] = {        ccp(offsetPix.x,offsetPix.y),ccp(offsetPix.x+s.wIDth,offsetPix.y+s.height),ccp(offsetPix.x,offsetPix.y+s.height)    };    ccDrawpoly(vertices,true);#endif // CC_SPRITE_DEBUG_DRAW        CC_INCREMENT_GL_DRAWS(1);        CC_PROfileR_Stop_category(kCCProfilercategorySprite,"CCSprite - draw");}

代码的功能和CCSprite的draw基本一致,唯一的差别如下:
    //绑定texOffset    getShaderProgram()->setUniformlocationWith2f(_uniformOffset,_autoScrollCountV);

该行代码将shader中的texOffset与update中的实时更新的uv关联起来。

本文源代码下载地址:http://download.csdn.net/detail/liangneo/8348147

使用说明:放到cocos2d-x的samples/Cpp/目录下替换原来的文件即可


BUGFix,由于cocos2d-x的spriteFrame可能只使用贴图中的一部分,因此使用UVSprite::createWithSpriteFramename创建出来的对象的uv只是0 --- 1范围中的一部分,使用上述shader可以会出错。作以下更正:

1.frag Shader

#ifdef GL_ES                                                            precision lowp float;                                                   #endif                                                                  varying vec4 v_fragmentcolor;                                           varying vec2 v_texCoord;                                                uniform vec2 texOffset;                                                 uniform sampler2D CC_Texture0;                                          uniform vec2 uRange;                                                    uniform vec2 vRange;                                                    voID main()                                                             {                                                                           vec2 texcoord = texOffset+v_texCoord;                                   texcoord.x = mod(texcoord.x - uRange.x,uRange.y-uRange.x) + uRange.x;       texcoord.y = mod(texcoord.y - vRange.x,vRange.y-vRange.x) + vRange.x;       gl_Fragcolor = v_fragmentcolor * texture2D(CC_Texture0,texcoord);			}    

增加了两个变量,uRange和vRange分别用来记录,uv的范围,确保精灵在的贴图在这个范围内

2.shader Load

voID UVSprite::loadShaderVertex(const char *vert,"texOffset");    _uniformURange = glGetUniformlocation(shader->getProgram(),"uRange");    _uniformVRange = glGetUniformlocation(shader->getProgram(),"vRange");    this->setShaderProgram(shader);        shader->release();}

在load时,绑定shader中的uRange和vRange

3.渲染

voID UVSprite::draw(){    CC_PROfileR_START_category(kCCProfilercategorySprite,m_sBlendFunc.dst );        //BUG fix with sprite frame        getShaderProgram()->setUniformlocationWith2f(_uniformURange,m_squad.bl.texCoords.u,m_squad.br.texCoords.u);    getShaderProgram()->setUniformlocationWith2f(_uniformVRange,m_squad.bl.texCoords.v,m_squad.tl.texCoords.v);    float offsetU = (m_squad.br.texCoords.u - m_squad.bl.texCoords.u) * _autoScrollCountU;    float offsetV = (m_squad.tl.texCoords.v - m_squad.bl.texCoords.v) * _autoScrollCountV;        getShaderProgram()->setUniformlocationWith2f(_uniformOffset,offsetU,offsetV);    //绑定纹理贴图    ccGLBindTexture2D( m_pobTexture->getname() );    ccGLEnabLevertexAttribs( kCCVertexAttribFlag_PoscolorTex );    #define kQuadSize sizeof(m_squad.bl)#ifdef EMSCRIPTEN    long offset = 0;    setGLBufferData(&m_squad,"CCSprite - draw");}
总结

以上是内存溢出为你收集整理的用cocos2d-x 实现UV动画--实现篇全部内容,希望文章能够帮你解决用cocos2d-x 实现UV动画--实现篇所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1031064.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存