Drawing 2D GUI over a 3D sketch

I’m making a 3D game, and a problem I ran into was drawing a 2D GUI over top of the main 3D sketch.
The solution I found is pretty simple, but it works really well:

  //IMPORTANT: make sure to use textMode(SHAPE) before using this!! Otherwise text will be drawn as black boxes.
  //GUI
  hint(DISABLE_DEPTH_TEST); //draws on top of whatever is drawn on screen
  camera(); //reset camera to default position, which conveniently lines up with the screen exactly
  ortho(); //orthographic projection removes any need for the z axis
  //start drawing whatever!
  fill(0);
  textSize(50);
  text("Test", 11, 110);
  hint(ENABLE_DEPTH_TEST); //re-enable depth test so the rest of the scene can be drawn normally
  //you can reset the camera to perspective now, or at the beginning of draw()

Make sure that this code runs last in draw(), because disabling the depth test will make any geometry drawn after the GUI ignore the depth of all geometry drawn before the GUI, resulting in weirdness.
The default camera position is the perfect position for a 2D canvas within a 3D scene since it automatically positions the (0, 0) and (width, height) coordinates at opposite corners of the screen, just like a regular 2D sketch. An orthographic projection is preferred over perspective to remove any possible z-axis or FOV influence. Also, the default parameters for the ortho() projection sets the clipping bounds to exactly surround (0, 0) and (width, height). It works out so nicely; it only requires 5 lines of code and you don’t even have to type a single number to set it up.

3 Likes

Great that you are sharing this @Shwaa!

I have been using something like this also:

pushMatrix();
resetMatrix();
// 2D stuff here
popMatrix();

And when I’m using wonderful PeasyCam orbit library (http://mrfeinberg.com/peasycam/):

camera.beginHUD();
// now draw things that you want 
camera.endHUD(); //
2 Likes