setup()
setup() runs once when the sketch starts. For 3D scenes, use createCanvas with WEBGL, configure perspective for depth perception, and initialize the camera position and direction. The camera is the viewer's eye in the 3D world.
function setup() {
// Create a WebGL canvas for 3D rendering
createCanvas(windowWidth, windowHeight, WEBGL);
// Set up a perspective camera
// For more on perspective(): https://p5js.org/reference/#/p5/perspective
perspective(PI / 3.0, width / height, 0.1, 1000);
// Initialize camera controls
cam = createCamera();
cam.setPosition(0, -50, zoomLevel); // CRITICAL FIX: Set initial camera Y to eye level (-50)
cam.lookAt(0, 0, 0); // Look towards the center of the scene
// Disable stroke for most objects for a cleaner look
noStroke();
}
Line-by-line explanation (6 lines)
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight, WEBGL);
Creates a full-window canvas with WebGL rendering enabled, which is required for 3D shapes and lighting
perspective(PI / 3.0, width / height, 0.1, 1000);
Configures perspective projection with a 60-degree field of view, proper aspect ratio, and near/far clipping planes
cam.setPosition(0, -50, zoomLevel);
cam.lookAt(0, 0, 0);
Places the camera at eye level (-50 on Y-axis) and points it toward the center, establishing the first-person viewpoint
createCanvas(windowWidth, windowHeight, WEBGL);- Creates a canvas that fills the entire window using WEBGL rendering mode, which enables 3D shapes, lighting, and materials—essential for this 3D room
perspective(PI / 3.0, width / height, 0.1, 1000);- Sets up perspective projection: PI/3.0 (60°) is the field of view, width/height maintains correct proportions, and 0.1 to 1000 define which distances are visible (near and far clipping planes)
cam = createCamera();- Creates a camera object that you can control with pan(), tilt(), and setPosition() for interactive first-person navigation
cam.setPosition(0, -50, zoomLevel);- Places the camera at the center X and Z (0, 0), slightly above the floor on Y (-50 for eye level), and zoomLevel pixels back (starting at 300)
cam.lookAt(0, 0, 0);- Points the camera toward the origin (0, 0, 0), the center of the room, so you start looking into the scene
noStroke();- Disables outlines on all shapes, giving them a smoother, more realistic appearance