How To Create and Draw a Rubik’s Cube

This article will focus on one method to build and render a Rubik’s Cube with GLSL Hacker and can be used as a basis for a more advanced animation of the Rubik’s Cube.

To create a Rubik’s Cube with GLSL Hacker, we just need a box mesh and an array that holds the parameters of each instance (only the position in this simple demo) of the box (or cube in our case).

The cube mesh will be used to render a cubelet, which is the name of one of the 26 small cubes that form the Rubik’s Cube.

We first need to know how to render a cubelet. Once this step is done, the rendering of the entire Rubik’s Cube is just a matter of drawing all cubelets at correct position.

To render a full Rubik’s Cube with correct colors, we just need to assign correct colors to the cubelet. According to wikipedia, the color of a face of the Rubik’s Cube follows this rule:

In a classic Rubik’s Cube, each of the six faces is covered by nine stickers, each of one of six solid colours: white, red, blue, orange, green, and yellow. In currently sold models, white is opposite yellow, blue is opposite green, and orange is opposite red, and the red, white and blue are arranged in that order in a clockwise arrangement.

This line of code creates a mesh cube with 36 vertices (6 vertices per face). This structure is not the most optimal structure for a cube (8 vertices are enough) but it allows to have several texture coordinates and several colors for a particular vertex. As I said, each face has 6 vertices and faces are organized like this:

Obviously, it's not the expected rotation. Why do we have this kind of rotation? Because of the order of internal transformation that build the final transformation matrix. By default in GLSL Hacker, the order of transformation is:

Transform = Translation * Rotation * Scale

The default transformation order is not suited to rotate the Rubik's Cube. We actually need another transformation order defined by:

Transform = Rotation * Translation * Scale

GLSL Hacker 0.8.0.3 introduces a new function that allows to change the transformation order: