setup()
setup() runs once when the sketch starts. Here it prepares two canvases: a full-screen one for display and a small low-res one where the actual game renders. This two-buffer technique is the foundation of pixel-perfect retro game graphics in p5.js.
function setup() {
pixelDensity(1); // important for crisp pixels
createCanvas(windowWidth, windowHeight);
noSmooth(); // disable smoothing when scaling buffer
gameG = createGraphics(GAME_W, GAME_H);
gameG.noSmooth(); // crisp shapes in buffer too
noiseSeed(worldSeed);
player = {
tileX: 0,
tileY: 0,
formIndex: 0,
hp: playerForms[0].maxHp,
maxHp: playerForms[0].maxHp,
facing: 'down'
};
}
Line-by-line explanation (7 lines)
🔧 Subcomponents:
pixelDensity(1);
createCanvas(windowWidth, windowHeight);
noSmooth();
Creates a full-window canvas and disables anti-aliasing so scaled pixels remain sharp and blocky
gameG = createGraphics(GAME_W, GAME_H);
gameG.noSmooth();
Creates the 256×192 offscreen buffer where all game drawing happens before scaling
player = {
tileX: 0,
tileY: 0,
formIndex: 0,
hp: playerForms[0].maxHp,
maxHp: playerForms[0].maxHp,
facing: 'down'
};
Sets up the player object with starting position, form, HP, and direction facing
pixelDensity(1);- Prevents p5.js from doubling pixels on high-DPI displays—ensures 1 logical pixel = 1 actual pixel for crisp scaling
createCanvas(windowWidth, windowHeight);- Creates the main display canvas at full window size so the player's screen real estate is used
noSmooth();- Disables anti-aliasing on the main canvas so when the game buffer is scaled up, pixels stay sharp and blocky
gameG = createGraphics(GAME_W, GAME_H);- Creates an offscreen graphics buffer at the low 'game' resolution (256×192) where all rendering happens
gameG.noSmooth();- Also disables smoothing on the game buffer so shapes drawn into it stay crisp
noiseSeed(worldSeed);- Seeds the random noise generator with a fixed value so the same tile coordinates always produce the same terrain type
player = { tileX: 0, tileY: 0, formIndex: 0, hp: playerForms[0].maxHp, maxHp: playerForms[0].maxHp, facing: 'down' };- Initializes the player object at tile (0, 0) as the first form (Duckling) with full HP and facing downward