setup()
setup() runs once when the sketch starts. It prepares the 3D scene by creating the canvas, initializing all objects and variables, and setting up interactive controls. Understanding setup() is crucial because every 3D sketch must establish its camera, lighting, and initial geometry here.
function setup() {
createCanvas(windowWidth, windowHeight, WEBGL);
perspective(fov, width / height, 0.1, 10000);
drawingContext.enable(drawingContext.DEPTH_TEST);
// Initialize starfield
for (let i = 0; i < numStars; i++) {
stars.push({
x: random(-2000, 2000),
y: random(-2000, 2000),
z: random(-2000, 2000),
brightness: random(100, 255)
});
}
// Initialize satellite position
satellitePos = createVector(400, 0, 0);
satelliteVel = createVector(0, 0, satelliteSpeed);
// Initialize UI controls
gravitySlider = createSlider(0.1, 2, 0.5, 0.05);
gravitySlider.position(20, 20);
speedSlider = createSlider(1, 8, 3, 0.5);
speedSlider.position(20, 50);
}
Line-by-line explanation (8 lines)
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight, WEBGL);
Creates a full-screen WEBGL canvas for 3D rendering
for (let i = 0; i < numStars; i++) { stars.push({...}); }
Populates the stars array with random star objects distributed throughout space
satellitePos = createVector(400, 0, 0);
Places the satellite at its starting orbital position
gravitySlider = createSlider(0.1, 2, 0.5, 0.05);
Creates interactive sliders to adjust gravity and speed in real time
createCanvas(windowWidth, windowHeight, WEBGL);- Creates a full-screen canvas with WEBGL rendering mode, which enables 3D graphics like lighting, camera control, and depth
perspective(fov, width / height, 0.1, 10000);- Sets up the camera's perspective view—objects closer to the camera appear larger, and those at depth 10000 are barely visible
drawingContext.enable(drawingContext.DEPTH_TEST);- Enables depth testing so that 3D objects correctly hide behind each other based on distance from camera
for (let i = 0; i < numStars; i++) {- Loops through and creates numStars (e.g., 1000) random star objects
stars.push({ x: random(-2000, 2000), y: random(-2000, 2000), z: random(-2000, 2000), brightness: random(100, 255) });- Adds each star as an object with random x, y, z positions in a large space and a random brightness value
satellitePos = createVector(400, 0, 0);- Places the satellite 400 units away from Earth's center on the x-axis as its starting position
satelliteVel = createVector(0, 0, satelliteSpeed);- Gives the satellite an initial velocity in the z direction so it starts moving in an orbit
gravitySlider = createSlider(0.1, 2, 0.5, 0.05);- Creates an interactive slider ranging from 0.1 to 2 with starting value 0.5 and step size 0.05