setup()
setup() runs once at startup and initializes all the variables and arrays your sketch needs. For responsive designs, use windowWidth and windowHeight instead of hard-coded numbers so the sketch scales to any screen size.
function setup() {
createCanvas(windowWidth, windowHeight);
vanishingPointY = height;
vanishingPointX = width / 2;
// Initialize car
carWidth = width * 0.05;
carHeight = height * 0.08;
carX = width / 2;
// Initialize road lines
for (let i = 0; i < numRoadLines; i++) {
roadLines.push({
y: map(i, 0, numRoadLines, height, 0), // Start from bottom, spaced out
height: height * 0.02, // Initial height of a dashed segment
width: width * 0.005, // Initial width of a dashed segment
});
}
// Initialize scenery
for (let i = 0; i < numSceneryItems; i++) {
scenery.push(createSceneryItem(i));
}
}
Line-by-line explanation (9 lines)
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight); vanishingPointY = height; vanishingPointX = width / 2;
Creates a full-screen canvas and sets the vanishing point at the center-bottom where all perspective lines converge
carWidth = width * 0.05; carHeight = height * 0.08; carX = width / 2;
Scales the car size relative to canvas dimensions and centers it horizontally
for (let i = 0; i < numRoadLines; i++) { roadLines.push({...}); }
Creates 20 dashed road segments spaced evenly from bottom to top using map() to distribute y-positions
for (let i = 0; i < numSceneryItems; i++) { scenery.push(createSceneryItem(i)); }
Populates the scenery array with 40 random trees and hills scattered across the landscape
createCanvas(windowWidth, windowHeight);- Creates a full-screen canvas that fills the entire browser window
vanishingPointY = height;- Sets the vanishing point's y-coordinate to the bottom of the screen, where perspective lines would converge
vanishingPointX = width / 2;- Centers the vanishing point horizontally, making the road appear to recede straight ahead
carWidth = width * 0.05;- Makes the car width 5% of the canvas width, so it scales responsively on different screen sizes
carHeight = height * 0.08;- Makes the car height 8% of canvas height for proper proportions
carX = width / 2;- Centers the car horizontally on the screen
y: map(i, 0, numRoadLines, height, 0),- Uses map() to spread the 20 road lines from bottom (y = height) to top (y = 0), creating even spacing
height: height * 0.02,- Sets each dashed segment's vertical thickness to 2% of canvas height
width: width * 0.005,- Sets each dashed segment's horizontal width to 0.5% of canvas width