uktu

This sketch creates an interactive game where a blue square player is controlled with arrow keys to move around a canvas that fills the entire window. The player stays within the canvas boundaries and the canvas automatically resizes when the window changes size.

🧪 Try This!

Experiment with the code by making these changes:

  1. Change the player color to red — The RGB values in fill() directly control color—change them to make the square red instead of blue
  2. Make the square twice as big — The playerSize variable controls the square's dimensions—double it to make it visually larger
  3. Make movement faster — The playerSpeed variable controls how far the square moves per frame—increase it for snappier controls
  4. Change the background to dark gray — The background() value goes from 0 (black) to 255 (white)—lower numbers create darker backgrounds
Prefer the full editor? Open it there →

📖 About This Sketch

This sketch animates a blue square that responds to arrow key presses, moving smoothly around a canvas that always fills your entire browser window. It teaches three essential p5.js techniques: keyboard input detection using keyIsDown(), boundary constraint checking using constrain(), and responsive canvas sizing with windowResized(). These are the foundational building blocks for any interactive game or interactive art project.

The code is organized into three functions: setup() initializes the canvas and player position, draw() runs every frame to handle animation and keyboard input, and windowResized() recalculates everything when your browser window changes. By studying it, you will learn how to make sketches that respond to user input and adapt to different screen sizes—skills you will use in every interactive project you build.

⚙️ How It Works

  1. When the sketch loads, setup() creates a canvas using windowWidth and windowHeight so it fills the entire browser window, then places the player square in the center
  2. Every frame, draw() clears the background and redraws the blue square at the player's current position
  3. Four if-statements check whether LEFT_ARROW, RIGHT_ARROW, UP_ARROW, or DOWN_ARROW are currently pressed using keyIsDown()
  4. When a key is pressed, the player's x or y position is adjusted by playerSpeed, moving the square in that direction
  5. Two constrain() calls lock the player's position so it cannot move past the edges of the canvas
  6. When you resize your browser window, windowResized() automatically stretches the canvas to fit and re-centers the player

🎓 Concepts You'll Learn

Keyboard input detectionBoundary constraint checkingResponsive canvas resizingVariable-based positioningConditional logic

📝 Code Breakdown

setup()

setup() runs exactly once when the sketch starts. Use it to initialize your canvas, set starting positions, and prepare any variables you need. The special variables windowWidth and windowHeight always contain your current browser window dimensions.

function setup() {
  createCanvas(windowWidth, windowHeight); // Tuval boyutunu pencere boyutuna ayarla
  // Tip: Kullanıcının pencere boyutuna uyumlu bir tuval için windowWidth/windowHeight kullanın

  // Oyuncuyu tuvalin ortasına yerleştir
  playerX = width / 2;
  playerY = height / 2;
}
Line-by-line explanation (3 lines)

🔧 Subcomponents:

function-call Canvas Setup createCanvas(windowWidth, windowHeight);

Creates a canvas that spans the entire browser window width and height

calculation Center Player playerX = width / 2; playerY = height / 2;

Positions the player square at the exact center of the canvas

createCanvas(windowWidth, windowHeight);
Creates a canvas with dimensions matching your browser window—it will stretch to fill the entire screen
playerX = width / 2;
Sets the player's starting horizontal position to the middle of the canvas (width divided by 2)
playerY = height / 2;
Sets the player's starting vertical position to the middle of the canvas (height divided by 2)

draw()

draw() runs 60 times per second, creating smooth animation. Every frame it clears the canvas, draws the square, checks for keyboard input, and enforces boundaries. This is the game loop—the heartbeat of any interactive sketch.

🔬 These two if-statements handle left and right movement. What happens if you change playerX -= playerSpeed to playerX -= playerSpeed * 2 so the left movement is twice as fast as the right?

  if (keyIsDown(LEFT_ARROW)) { // Sol ok tuşuna basıldıysa
    playerX -= playerSpeed; // Kareyi sola hareket ettir
  }
  if (keyIsDown(RIGHT_ARROW)) { // Sağ ok tuşuna basıldıysa
    playerX += playerSpeed; // Kareyi sağa hareket ettir
  }

🔬 These lines are the invisible walls that trap your square inside the canvas. What happens if you change playerSize / 2 to 0 in the left boundary so the square can partially leave the left edge?

  playerX = constrain(playerX, playerSize / 2, width - playerSize / 2);
  playerY = constrain(playerY, playerSize / 2, height - playerSize / 2);
function draw() {
  background(220); // Her karede arka planı griye boyayarak önceki çizimleri sil

  // Oyuncu karesini çiz
  fill(0, 100, 200); // Mavi renk
  rectMode(CENTER); // rect() fonksiyonunun karenin merkezinden çizmesini sağla
  rect(playerX, playerY, playerSize, playerSize); // Karenin konumunu ve boyutunu kullan

  // Klavye tuşlarına göre oyuncuyu hareket ettir
  // keyIsDown() fonksiyonu, bir tuşa basılıp basılmadığını kontrol eder.
  // https://p5js.org/reference/p5/keyIsDown/
  if (keyIsDown(LEFT_ARROW)) { // Sol ok tuşuna basıldıysa
    playerX -= playerSpeed; // Kareyi sola hareket ettir
  }
  if (keyIsDown(RIGHT_ARROW)) { // Sağ ok tuşuna basıldıysa
    playerX += playerSpeed; // Kareyi sağa hareket ettir
  }
  if (keyIsDown(UP_ARROW)) { // Yukarı ok tuşuna basıldıysa
    playerY -= playerSpeed; // Kareyi yukarı hareket ettir
  }
  if (keyIsDown(DOWN_ARROW)) { // Aşağı ok tuşuna basıldıysa
    playerY += playerSpeed; // Kareyi aşağı hareket ettir
  }

  // Karenin tuval sınırları içinde kalmasını sağla
  // constrain() fonksiyonu, bir değeri belirli bir aralıkta tutar.
  // https://p5js.org/reference/p5/constrain/
  playerX = constrain(playerX, playerSize / 2, width - playerSize / 2);
  playerY = constrain(playerY, playerSize / 2, height - playerSize / 2);
}
Line-by-line explanation (14 lines)

🔧 Subcomponents:

function-call Clear Canvas background(220);

Fills the entire canvas with light gray, erasing the previous frame

function-call Draw Player Square fill(0, 100, 200); // Mavi renk rectMode(CENTER); rect(playerX, playerY, playerSize, playerSize);

Sets the color to blue, ensures the square is drawn from its center point, and renders the square at the current position

conditional Left Arrow Handler if (keyIsDown(LEFT_ARROW)) { playerX -= playerSpeed; }

Checks if the left arrow key is pressed, and if so, decreases playerX to move the square left

conditional Right Arrow Handler if (keyIsDown(RIGHT_ARROW)) { playerX += playerSpeed; }

Checks if the right arrow key is pressed, and if so, increases playerX to move the square right

conditional Up Arrow Handler if (keyIsDown(UP_ARROW)) { playerY -= playerSpeed; }

Checks if the up arrow key is pressed, and if so, decreases playerY to move the square up

conditional Down Arrow Handler if (keyIsDown(DOWN_ARROW)) { playerY += playerSpeed; }

Checks if the down arrow key is pressed, and if so, increases playerY to move the square down

function-call Boundary Lock playerX = constrain(playerX, playerSize / 2, width - playerSize / 2); playerY = constrain(playerY, playerSize / 2, height - playerSize / 2);

Ensures the player cannot move outside the canvas edges by clamping x and y within valid ranges

background(220);
Fills the entire canvas with a light gray color (220 on a 0-255 scale), erasing everything drawn in the previous frame
fill(0, 100, 200);
Sets the fill color to blue using RGB values: 0 red, 100 green, 200 blue
rectMode(CENTER);
Tells rect() to draw rectangles from their center point—without this, rect() would draw from the top-left corner
rect(playerX, playerY, playerSize, playerSize);
Draws a square at position (playerX, playerY) with width and height both equal to playerSize pixels
if (keyIsDown(LEFT_ARROW)) {
Checks whether the left arrow key is currently being held down—this allows smooth, continuous movement
playerX -= playerSpeed;
Decreases playerX by playerSpeed pixels, moving the square to the left
if (keyIsDown(RIGHT_ARROW)) {
Checks whether the right arrow key is currently being held down
playerX += playerSpeed;
Increases playerX by playerSpeed pixels, moving the square to the right
if (keyIsDown(UP_ARROW)) {
Checks whether the up arrow key is currently being held down
playerY -= playerSpeed;
Decreases playerY by playerSpeed pixels, moving the square upward (y increases downward in p5.js)
if (keyIsDown(DOWN_ARROW)) {
Checks whether the down arrow key is currently being held down
playerY += playerSpeed;
Increases playerY by playerSpeed pixels, moving the square downward
playerX = constrain(playerX, playerSize / 2, width - playerSize / 2);
Forces playerX to stay between playerSize/2 (left edge) and width - playerSize/2 (right edge), preventing the square from moving off-screen horizontally
playerY = constrain(playerY, playerSize / 2, height - playerSize / 2);
Forces playerY to stay between playerSize/2 (top edge) and height - playerSize/2 (bottom edge), preventing the square from moving off-screen vertically

windowResized()

windowResized() is a special p5.js function that automatically runs whenever the browser window is resized. It's the perfect place to recalculate anything that depends on canvas size, like player position, boundary limits, or responsive layouts.

function windowResized() {
  resizeCanvas(windowWidth, windowHeight); // Pencere boyutu değiştiğinde tuvali yeniden boyutlandır
  // Önizleme paneli yeniden boyutlandırıldığında çağrılır

  // Yeniden boyutlandırmadan sonra oyuncuyu tekrar ortala
  playerX = width / 2;
  playerY = height / 2;
}
Line-by-line explanation (3 lines)

🔧 Subcomponents:

function-call Resize Canvas resizeCanvas(windowWidth, windowHeight);

Stretches the canvas to match the new window dimensions

calculation Recenter Player playerX = width / 2; playerY = height / 2;

Places the player back at the center of the newly sized canvas

resizeCanvas(windowWidth, windowHeight);
Automatically resizes the p5.js canvas to match your current browser window dimensions—essential for making sketches that work on any screen size
playerX = width / 2;
Recalculates the player's horizontal center position after the canvas has been resized
playerY = height / 2;
Recalculates the player's vertical center position after the canvas has been resized

📦 Key Variables

playerX number

Stores the current horizontal position (x-coordinate) of the player square on the canvas

let playerX = 200;
playerY number

Stores the current vertical position (y-coordinate) of the player square on the canvas

let playerY = 200;
playerSize number

Defines the width and height of the player square in pixels

let playerSize = 50;
playerSpeed number

Controls how many pixels the square moves each frame when an arrow key is pressed

let playerSpeed = 5;

🔧 Potential Improvements (4)

Here are some ways this code could be enhanced:

STYLE draw() - keyboard input handling

Four separate if-statements for arrow keys is repetitive and makes the code longer than necessary

💡 Use a single object or map to store key states, or use a switch statement to handle all directional input more concisely

FEATURE draw()

No visual feedback or game mechanics—the sketch is just movement with no goals or interaction beyond moving the square

💡 Add obstacles to avoid, targets to reach, or collectible objects to make it a real game with gameplay loop and win conditions

STYLE Code comments

Comments are written entirely in Turkish, which may not be accessible to all learners

💡 Consider translating comments to English for broader accessibility, or provide bilingual comments that serve international audiences

PERFORMANCE draw()

rectMode(CENTER) is called every frame even though it never changes

💡 Move rectMode(CENTER) to setup() since it only needs to be set once, reducing unnecessary function calls per frame

🔄 Code Flow

Code flow showing setup, draw, windowresized

💡 Click on function names in the diagram to jump to their code

graph TD start[Start] --> setup[setup] setup --> canvas-creation[Canvas Setup] canvas-creation --> player-centering[Center Player] player-centering --> draw[draw loop] draw --> background-clear[Clear Canvas] background-clear --> square-drawing[Draw Player Square] square-drawing --> left-movement[Left Arrow Handler] square-drawing --> right-movement[Right Arrow Handler] square-drawing --> up-movement[Up Arrow Handler] square-drawing --> down-movement[Down Arrow Handler] left-movement --> boundary-constraint[Boundary Lock] right-movement --> boundary-constraint up-movement --> boundary-constraint down-movement --> boundary-constraint boundary-constraint --> draw click setup href "#fn-setup" click draw href "#fn-draw" click canvas-creation href "#sub-canvas-creation" click player-centering href "#sub-player-centering" click background-clear href "#sub-background-clear" click square-drawing href "#sub-square-drawing" click left-movement href "#sub-left-movement" click right-movement href "#sub-right-movement" click up-movement href "#sub-up-movement" click down-movement href "#sub-down-movement" click boundary-constraint href "#sub-boundary-constraint" draw --> windowresized[windowResized] windowresized --> canvas-resize[Resize Canvas] canvas-resize --> player-recenter[Recenter Player] player-recenter --> draw click windowresized href "#fn-windowresized" click canvas-resize href "#sub-canvas-resize" click player-recenter href "#sub-player-recenter"

❓ Frequently Asked Questions

What visual elements are featured in the uktu p5.js sketch?

The uktu sketch creates a simple visual representation of a blue square that can be moved around the canvas.

How can users interact with the uktu sketch?

Users can control the movement of the blue square using the arrow keys on their keyboard.

What creative coding concepts are illustrated in the uktu sketch?

The sketch demonstrates basic concepts of user input handling, object movement, and boundary constraints in a 2D environment.

Preview

uktu - p5.js creative coding sketch preview
Sketch Preview
Code flow diagram showing the structure of uktu - Code flow showing setup, draw, windowresized
Code Flow Diagram