Drawing 3D Shapes With Processing
In the first tutorial in this series, I’m going to show you how to draw basic shapes like cubes and spheres with the P3D and OpenGL renderers. The sketches I’m using in this tutorial are available for download at the bottom of the page.
The P3D Renderer
This is a basic rendering engine for 3D shapes and it uses the CPU of your computer to do the math. To use this renderer, you’ll need to add a third parameter to the
size(800, 600, P3D);
To start drawing things in 3D, we’ll start with the most basic shape: a box. You can use the
box() function with one parameter to create a cube or with three parameters to draw a box with a different width, height and depth.
// Draw a cube
// Draw a box
box(50, 40, 100);
The code for the cube and the box can be found in the sketch
box_p3d.pde. This is what the result of the sketch looks like.
Another basic shape to draw is a sphere. The
sphere() function takes one parameter: the radius. To draw a sphere with a radius of 40 pixels, you’ll need to use the code below.
sphereDetail() function can be used to change the way your sphere looks. If you don’t use this function, Processing will use the default setting of 30. You can use the function with one or two parameters. Play around to see what happens.
The image below shows you what the three spheres look like. The code for this sketch can be found in
Turn the Lights on
To add more depth to your sketch, you’ll need to turn on the lights in your sketch by using the
lights() function. To get the best result, you also need to turn of strokes with the
noStroke() function. The light will add shadows to your objects and they will look more like real 3D shapes. You can find the code in the sketch
The OpenGL Renderer
If you want your sketches to run faster, you can use the OpenGL renderer. But before you can use it, you’ll need to import the OpenGL library to your sketch. OpenGL is a high speed 3D renderer that uses the graphics card in your computer. Most high-end Macs and gaming computers have a graphics card that is OpenGL compatible.
size(800, 600, OPENGL);
Try running the
lights_opengl.pde sketch and see the difference.
Download the sketches I’ve used in this tutorial and let me know in the comments if you find the article useful.