setup()
setup() runs exactly once when the sketch starts. It is the place to create the canvas, initialize game objects, and configure p5.js settings. Understanding object literals like the car object is essential to game development—each property (x, y, speed, etc.) stores a piece of the car's state.
function setup() {
createCanvas(windowWidth, windowHeight);
// Car starts near "Midtown Manhattan"
car = {
x: 0,
y: 0,
angle: 0, // 0 rad = facing right (east)
speed: 0,
maxSpeed: 12,
accel: 0.4,
friction: 0.08,
turnRate: 0.06
};
layoutTouchControls();
textFont('sans-serif');
}
Line-by-line explanation (12 lines)
🔧 Subcomponents:
createCanvas(windowWidth, windowHeight);
Creates a full-screen canvas that fills the entire browser window
car = { x: 0, y: 0, angle: 0, speed: 0, maxSpeed: 12, accel: 0.4, friction: 0.08, turnRate: 0.06 };
Creates the car object with position, physics properties, and steering parameters
layoutTouchControls();
Places the joystick and gas button in the correct positions for the current screen size
createCanvas(windowWidth, windowHeight);- Creates a canvas that fills the entire browser window, responsive to any screen size
car = {- Begins defining the car object that will store position, velocity, and physics parameters
x: 0,- Car's horizontal position starts at world coordinate 0 (center)
y: 0,- Car's vertical position starts at world coordinate 0 (center)
angle: 0, // 0 rad = facing right (east)- Car's rotation in radians; 0 means facing right (east), PI/2 means facing down (south)
speed: 0,- Current velocity; positive values move the car forward, negative values move it backward
maxSpeed: 12,- The highest speed the car can reach; prevents unlimited acceleration
accel: 0.4,- How much speed increases each frame when the accelerator is pressed—higher = faster acceleration
friction: 0.08,- How quickly the car slows down when no input is given—simulates rolling resistance
turnRate: 0.06- How many radians the car rotates per frame when steering; controls turning speed
layoutTouchControls();- Calls a function to position the joystick and gas button for the current screen size
textFont('sans-serif');- Sets the font used for HUD text (speed display, instructions) to a clean sans-serif typeface