setup()
setup() runs once when the sketch loads and initializes the physics engine, game world, and initial level. Every p5.js sketch needs a setup() function to prepare the canvas and variables before draw() begins.
function setup() {
createCanvas(windowWidth, windowHeight);
engine = Engine.create();
world = engine.world;
world.gravity.y = 1.2;
// Setup initial player state (Active Mode)
activePlayer = Bodies.rectangle(100, height - 200, 35, 70, {
inertia: Infinity, // Prevents tipping over
friction: 0.05,
frictionAir: 0.01,
restitution: 0,
label: 'player'
});
Composite.add(world, activePlayer);
// Generate initial chunks
generateChunk();
generateChunk();
// Collisions
Matter.Events.on(engine, 'collisionStart', handleCollisions);
// UI
createMobilePads();
}
Line-by-line explanation (10 lines)
🔧 Subcomponents:
engine = Engine.create();
world = engine.world;
world.gravity.y = 1.2;
Creates a Matter.js physics engine and world with downward gravity
activePlayer = Bodies.rectangle(100, height - 200, 35, 70, { inertia: Infinity, friction: 0.05, frictionAir: 0.01, restitution: 0, label: 'player' });
Spawns the player as a rigid rectangle at the left side of the screen
generateChunk();
generateChunk();
Generates two chunks of terrain ahead of the player before the game starts
Matter.Events.on(engine, 'collisionStart', handleCollisions);
Registers a function to run whenever two bodies collide
createCanvas(windowWidth, windowHeight);- Creates a p5.js canvas that fills the entire browser window
engine = Engine.create();- Creates a new Matter.js physics engine that will update all bodies and simulate gravity
world = engine.world;- Gets a reference to the world (the container holding all physics bodies) from the engine
world.gravity.y = 1.2;- Sets downward gravity strength to 1.2; higher numbers pull bodies down faster
activePlayer = Bodies.rectangle(100, height - 200, 35, 70, { ... });- Creates a rigid rectangle body for the player at x=100, y=height-200, width=35, height=70
inertia: Infinity,- Prevents the rectangle from tipping over; it always stays upright
Composite.add(world, activePlayer);- Adds the player body to the physics world so it is simulated
generateChunk(); generateChunk();- Generates two chunks of platforms, coins, and spikes ahead
Matter.Events.on(engine, 'collisionStart', handleCollisions);- Listens for collisions and calls handleCollisions() when a collision begins
createMobilePads();- Creates on-screen touch buttons for left, right, jump, and ragdoll toggle