Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw grid lines in OpenGL ES Android?

I want to draw 10 by 10 grid that defines ground plane such that the center is the origin of the world coordinates. This is the code that is called for each line defined in the grid.

gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();

gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);

gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVerticesBuffer);

gl.glTranslatef(x, y, z);
gl.glRotatef(rz, 0, 0, 1);
gl.glRotatef(rx, 1, 0, 0);
gl.glRotatef(ry, 0, 1, 0);

gl.glDrawArrays(GL10.GL_LINES, 0, 2);

gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);

The problem is I only see one horizontal line. So I think something is wrong.

This is the code that defines the lines:

Line line;

for (int i = 0; i <= 10; i++) {
    // horizontal lines
    line =  new Line(-50, 0, 0, 50, 0, 0, 0, 0, 1, 1);  // blue line
    line.z = (i * 100) - 50;
    lines.add(line);

    // draw perspective lines
    line =  new Line(-50, 0, 0, 50, 0, 0, 0, 0, 1, 1);  // blue line
    line.x = (i * 100) - 50;
    line.ry = 90; 
    lines.add(line);
}

For each line in the lines collection I call the drawing code in onDrawFrame.

like image 852
ace Avatar asked Oct 11 '22 14:10

ace


1 Answers

The reason is because you are only drawing one line. glDrawArrays basically draws opengl primitives from the data given. So the coordinates in your buffer mVerticesBuffer are being drawn once by glDrawArrays.

A simple way to do what you want is to:

  • Rotate/Translate to starting position
  • Draw your first line with glDrawArrays();
  • Use gl.glTranslatef(somenumber, 0, 0);
  • Draw again with the same call to glDrawArrays();
  • Use gl.glRotatef(90, 0, 1, 0); to rotate around the y-axis (Or whichever axis you are 0 in)
  • (Maybe translate back in an axis to get to the same start position)
  • Do the 2nd, 3rd and 4th bullet point again.

A much tidier and more efficient way of doing this would be with pushing and popping matrices but for simplicity this should work if you're new to opengl.

like image 128
Infiniti Fizz Avatar answered Nov 15 '22 12:11

Infiniti Fizz