Reputation: 14196
I am trying to draw a circle in opengl-es using the following code. It creates a number of points around a circle. If I print out the values in the vertex array it can be seen that they form points around a circle.
// Create verticies for a circle
points=40;
vertices = new float[(points+1)*3];
//CENTER OF CIRCLE
vertices[0]=0.0f;
vertices[1]=0.0f;
vertices[2]=0.0f;
for (int i = 3; i<(points+1)*3; i+=3){
double rad = deg2rad(i*360/points);
vertices[i] = (float) (Math.cos(rad));
vertices[i+1] = (float) (Math.sin(rad));
vertices[i+2] = 0;
}
// vertexBuffer is filled with verticies
And the calls to opengl in my drawing function:
// IN MY DRAWING FUNCTION:
gl.glPushMatrix();
gl.glTranslatef(x, y, 0);
gl.glScalef(size, size, 1.0f);
gl.glColor4f(1.0f,1.0f,1.0f, 1.0f);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glDrawArrays(GL10.GL_TRIANGLE_FAN, 0, points/2);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
gl.glPopMatrix();
However I never get a circle drawn to the screen, only ever a square. I am very confused, any help is appreciated :)
Upvotes: 2
Views: 8437
Reputation: 5959
//...vertex and index buffers...
int VERTICES=180; // more than needed // changed variable name
float coords[] = new float[VERTICES * 3];
float theta = 0;
for (int i = 0; i < VERTICES * 3; i += 3) {
coords[i + 0] = (float) Math.cos(theta);
coords[i + 1] = (float) Math.sin(theta);
coords[i + 2] = 0;
vertexBuffer.put(coords[i + 0]);
vertexBuffer.put(coords[i + 1]);
vertexBuffer.put(coords[i + 2]);
theta += Math.PI / 90;
}
// ....set buffer positions to zero...
protected void draw(GL10 gl) {
gl.glColor4f(0, 0, 1, 0.5f);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, vertexBuffer);
gl.glDrawElements(GL10.GL_TRIANGLE_FAN, VERTICES,
GL10.GL_UNSIGNED_SHORT, indexBuffer);
}
}
Easy breezy.
Upvotes: 2
Reputation: 1484
one thing that looks wrong is the calculation of rad
. Try modifying it to something like:
double rad = deg2rad(i*360/(points*3));
You need to divide it by points*3
because the i
counter is getting incremented by 3 on each iteration. You should print out the value of rad
on each iteration and verify that you're getting values incrementing between 0 and 2 * PI
EDIT: you may also need to change the direction of the circle (i'm not sure at the top of my head). but if the above doesn't render anything, try reversing it:
double rad = deg2rad(360.0 - i*360/(points*3));
Also, it looks like you're only rendering half the points in the glDrawArrays
call.
Upvotes: 2