class QuadSprite : public CCSprite{ public: static QuadSprite* createQuadSprite(ccVertex2F *vertexs,CCTexture2D* texture); bool initWithVertices(ccVertex2F *vertexs); virtual void draw(); private: // 需要提供四个点 // 顺序为 // 0 leftUp // 1 leftDown // 2 RightUp // 3 RightDown ccVertex2F mVertexs[4]; };
#include "QuadSprite.h" //三角形索引 const static unsigned short kIndices[6] = {0,1,2,1,3,2}; const static ccVertex2F kUVS[] = { {0.0,0.0}, {0.0,1.0}, {1.0,0.0}, {1.0,1.0} }; const static unsigned char kColors[] = {255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,}; QuadSprite* QuadSprite::createQuadSprite(ccVertex2F* vertexs,CCTexture2D* texture) { QuadSprite* bob = new QuadSprite; if (bob && bob->initWithTexture(texture) && bob->initWithVertices(vertexs)) { bob->autorelease(); return bob; } CC_SAFE_DELETE(bob); return NULL; } bool QuadSprite::initWithVertices(ccVertex2F *vertexs) { // 内存分配 for (int i = 0; i < 4; ++i) { mVertexs[i].x = vertexs[i].x; mVertexs[i].y = vertexs[i].y; } return true; } // 设置纹理坐标 //m_sQuad.bl.texCoords.u = 0.0; //m_sQuad.bl.texCoords.v = 1.0; // //m_sQuad.br.texCoords.u = 1.0; //m_sQuad.br.texCoords.v = 1.0; // //m_sQuad.tl.texCoords.u = 0.0; //m_sQuad.tl.texCoords.v = 0.0; // //m_sQuad.tr.texCoords.u = 1.0; //m_sQuad.tr.texCoords.v = 0.0; void QuadSprite::draw() { CC_NODE_DRAW_SETUP(); ccGLBlendFunc( m_sBlendFunc.src, m_sBlendFunc.dst ); if (m_pobTexture != NULL) { ccGLBindTexture2D( m_pobTexture->getName() ); } else { ccGLBindTexture2D(0); } // // Attributes // ccGLEnableVertexAttribs(kCCVertexAttribFlag_PosColorTex); //顶点,纹理,颜色 glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, mVertexs); glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, 0, kUVS); glVertexAttribPointer(kCCVertexAttrib_Color, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, kColors); //根据索引draw三角形 glDrawElements(GL_TRIANGLES,6, GL_UNSIGNED_SHORT, kIndices); CHECK_GL_ERROR_DEBUG(); CC_INCREMENT_GL_DRAWS(1); }
使用示例:
// ccVertex2F mVertices[] = { // {100,100}, // {100,50}, // {300,100}, // {300,50}, // }; // QuadSprite* qsp = QuadSprite::createQuadSprite(mVertices, mTex); // qsp->setAnchorPoint(ccp(0, 0)); // addChild(qsp);