Draw cube with OpenGL in a for-loop

As long as you use glutSolidCube in OpenGL, drawing a cube isn't hard. With Java OpenGL (JOGL), it's not as obvious, since you need the special import com.sun.opengl.util.GLUT to use the glutXXX()-methods. Another approach is to write your own version with the OpenGL primitives. If you don't want to think about all those needed coordinates, you can also try to rotate one face of the cube six times to create the cube.

Following Scala-code uses this principle:

gl.glPushMatrix
for (val i <- 1 to 6) {
  gl.glRotated(90, if (i % 2 == 0) 1 else 0, if ((i-1) % 2 == 0) 1 else 0, 0)
  gl.glBegin(GL.GL_POLYGON)
  gl.glVertex3d(-0.5, -0.5, 0.5)
  gl.glVertex3d(0.5, -0.5, 0.5)
  gl.glVertex3d(0.5, 0.5, 0.5)
  gl.glVertex3d(-0.5, 0.5, 0.5)
  gl.glEnd
}
gl.glPopMatrix

Here you can see, that the face will be alternately rotated by 90° on the x-axis or the y-axis. Does this principle work with different kinds of faces and angles?

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd><h2> <h3> <h4> <h5> <h6>
  • Syntax highlight code surrounded by the {syntaxhighlighter SPEC}...{/syntaxhighlighter} tags, where SPEC is a Syntaxhighlighter options string or class="OPTIONS" [title="the title"].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.