现在的位置: 首页 > 综合 > 正文

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

2018年05月27日 ⁄ 综合 ⁄ 共 8455字 ⁄ 字号 评论关闭

用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, GL_FLOAT, GL_FALSE, kQuadSize, (void*)(offset + diff));
    
    // 设置顶点颜色
    diff = offsetof( ccV3F_C4B_T2F, colors);
    glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (void*)(offset + diff));
    
    //渲染矩形
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 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, 4, 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),
        ccp(offsetPix.x+s.width,offsetPix.y+s.height), ccp(offsetPix.x,offsetPix.y+s.height)
    };
    ccDrawPoly(vertices, 4, true);
#endif // CC_SPRITE_DEBUG_DRAW
    
    CC_INCREMENT_GL_DRAWS(1);
    
    CC_PROFILER_STOP_CATEGORY(kCCProfilerCategorySprite, "CCSprite - draw");

}

代码的功能和CCSprite的draw基本一致,唯一的差别如下:

    //绑定texOffset
    getShaderProgram()->setUniformLocationWith2f(_uniformOffset, _AutoScrollCountU, _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, 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");
    _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, "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 );
    
    //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, 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, GL_FLOAT, GL_FALSE, kQuadSize, (void*)(offset + diff));
    
    // 设置顶点颜色
    diff = offsetof( ccV3F_C4B_T2F, colors);
    glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, kQuadSize, (void*)(offset + diff));
    
    //渲染矩形
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 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, 4, 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),
        ccp(offsetPix.x+s.width,offsetPix.y+s.height), ccp(offsetPix.x,offsetPix.y+s.height)
    };
    ccDrawPoly(vertices, 4, true);
#endif // CC_SPRITE_DEBUG_DRAW
    
    CC_INCREMENT_GL_DRAWS(1);
    
    CC_PROFILER_STOP_CATEGORY(kCCProfilerCategorySprite, "CCSprite - draw");

}

抱歉!评论已关闭.