cocos2d-x提供了完整的openGL ES支持,但是gl是个非常难用的东西,所以cocos2d-x提供了对一些常用图形的封装。
具体的使用方法在tests中的DrawPrimitivesTest有过体现。
最近做开发需要在sprite中通过draw画圆,但是cocos2d-x封装的ccDrawCircle函数只能画空心圆。我们只需要稍微改造一下这个函数就能绘制一个实心圆。
改造方法很简单:
1,找到ccDrawCircle函数的实现(CCDrawingPrimitives.cpp),复制一份,并且将其中的“GL_LINE_STRIP”替换成“GL_TRIANGLE_FAN”就可以了。例如:
void ccDrawSolidCircle( const CCPoint& center, float radius, float angle, unsigned int segments, bool drawLineToCenter, float scaleX, float scaleY)
{
lazy_init();
int additionalSegment = 1;
if (drawLineToCenter)
additionalSegment++;
const float coef = 2.0f * (float)M_PI/segments;
GLfloat *vertices = (GLfloat*)calloc( sizeof(GLfloat)*2*(segments+2), 1);
if( ! vertices )
return;
for(unsigned int i = 0;i <= segments; i++) {
float rads = i*coef;
GLfloat j = radius * cosf(rads + angle) * scaleX + center.x;
GLfloat k = radius * sinf(rads + angle) * scaleY + center.y;
vertices[i*2] = j;
vertices[i*2+1] = k;
}
vertices[(segments+1)*2] = center.x;
vertices[(segments+1)*2+1] = center.y;
s_pShader->use();
s_pShader->setUniformsForBuiltins();
s_pShader->setUniformLocationWith4fv(s_nColorLocation, (GLfloat*) &s_tColor.r, 1);
ccGLEnableVertexAttribs( kCCVertexAttribFlag_Position );
#ifdef EMSCRIPTEN
setGLBufferData(vertices, sizeof(GLfloat)*2*(segments+2));
glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, 0);
#else
glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, vertices);
#endif // EMSCRIPTEN
glDrawArrays(GL_TRIANGLE_FAN, 0, (GLsizei) segments+additionalSegment);
free( vertices );
CC_INCREMENT_GL_DRAWS(1);
}
void CC_DLL ccDrawSolidCircle( const CCPoint& center, float radius, float angle, unsigned int segments, bool drawLineToCenter)
{
ccDrawSolidCircle(center, radius, angle, segments, drawLineToCenter, 1.0f, 1.0f);
}
然后记得在头文件里头添加上函数声明
void CC_DLL ccDrawSolidCircle( const CCPoint& center, float radius, float angle, unsigned int segments, bool drawLineToCenter, float scaleX, float scaleY);
void CC_DLL ccDrawSolidCircle( const CCPoint& center, float radius, float angle, unsigned int segments, bool drawLineToCenter);