setup()
setup() runs once when the sketch first loads. It's where you create your canvas, initialize variables, load external assets (like sounds), and set up the UI. This is the perfect place to establish colors, sizes, and game constants that stay the same for the entire sketch.
function setup() {
createCanvas(windowWidth, windowHeight);
mechSkin = {
body: color(70, 180, 255),
trim: color(255, 255, 255, 120),
core: color(255, 150, 0),
};
thrusterColor = color(0, 255, 255, 180);
initStars();
resetGame();
if (shootSound) shootSound.setVolume(0.2);
if (hitSound) hitSound.setVolume(0.3);
if (upgradeSound) upgradeSound.setVolume(0.4);
startButton = createButton('START MISSION');
startButton.addClass('start-btn');
startButton.mousePressed(() => {
if (!gameStarted || gameOver) {
resetGame();
gameStarted = true;
}
});
userStartAudio();
}
Line-by-line explanation (10 lines)
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight);
Creates a full-screen canvas that covers the entire browser window
mechSkin = {
body: color(70, 180, 255),
trim: color(255, 255, 255, 120),
core: color(255, 150, 0),
};
Defines the RGB colors for the player mech's body, trim, and core so it looks cohesive and glowing
startButton = createButton('START MISSION');
startButton.addClass('start-btn');
startButton.mousePressed(() => {
if (!gameStarted || gameOver) {
resetGame();
gameStarted = true;
}
});
Creates a clickable START MISSION button with CSS styling that resets and starts the game
createCanvas(windowWidth, windowHeight);- Makes a canvas as large as the browser window so the game fills the entire screen
mechSkin = { body: color(70, 180, 255), trim: color(255, 255, 255, 120), core: color(255, 150, 0), };- Stores three RGB colors in an object so you can reuse them when drawing the player mech without repeating color() calls
thrusterColor = color(0, 255, 255, 180);- Pre-defines the cyan thruster color so it matches everywhere and can be changed in one place
initStars();- Calls the function that populates the stars array with 200 random starfield points for the background animation
resetGame();- Initializes the player and empties all the enemy, projectile, and power-up arrays to prepare a fresh game state
if (shootSound) shootSound.setVolume(0.2);- Sets the volume of the shoot sound to 20% only if it successfully loaded from the web URL
startButton = createButton('START MISSION');- Creates a DOM button element with the text START MISSION that will appear on screen
startButton.addClass('start-btn');- Applies the CSS class 'start-btn' from style.css to style the button with cyan border and glow effects
startButton.mousePressed(() => { ... });- Defines a callback function that fires when the button is clicked, resetting and starting the game
userStartAudio();- p5.sound helper that enables audio playback by asking the browser for permission on first user interaction