用cocos2d-x openGL ES畫實心圓
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);