setup()
setup() runs once when the sketch starts. It configures the canvas and initializes all the starting values your sketch needs. Notice how angleMode(RADIANS) and rectMode(CENTER) set the 'rules' for how p5.js will interpret your draw commands—these two lines are the foundation for everything that happens later.
function setup() {
createCanvas(windowWidth, windowHeight);
robotX = width / 2;
robotY = height / 2; // Store original Y position
rectMode(CENTER); // Draw rectangles from their center
angleMode(RADIANS); // Ensure rotation angles are in radians
// Assign value to armAnimationAmplitude here, where PI is defined
armAnimationAmplitude = PI / 4; // Max swing angle (e.g., 45 degrees from vertical)
}
Line-by-line explanation (6 lines)
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight);
Creates a canvas that fills the entire browser window
robotX = width / 2;
Places the robot horizontally in the center of the canvas
rectMode(CENTER); // Draw rectangles from their center
Makes all rectangles draw from their center point instead of top-left, simplifying positioning logic
angleMode(RADIANS); // Ensure rotation angles are in radians
Configures p5.js to interpret all angles as radians rather than degrees, required for sin() and cos() to work correctly
createCanvas(windowWidth, windowHeight);- Creates a canvas that stretches to fill the entire browser window, so the robot scales with screen size
robotX = width / 2;- Calculates the center X coordinate of the canvas and stores it in robotX so the robot draws in the middle horizontally
robotY = height / 2; // Store original Y position- Calculates the center Y coordinate and stores it so the robot starts in the middle vertically—this value stays fixed even when the robot bounces
rectMode(CENTER); // Draw rectangles from their center- Tells p5.js that all rect() calls should draw from their center point; without this, positioning calculations would be much more confusing
angleMode(RADIANS); // Ensure rotation angles are in radians- Sets angle measurement to radians (where TWO_PI = 360 degrees) so that sin(), cos(), and rotate() work with the math.js functions correctly
armAnimationAmplitude = PI / 4; // Max swing angle (e.g., 45 degrees from vertical)- Calculates the maximum arm swing angle as 45 degrees (PI/4 radians)—this defines how far the arms swing side to side