Code Play Games

Login

Register

How to Move a Player: A Step-by-Step Tutorial

In this post, I’ll walk you through the main logic and concepts behind a simple HTML, CSS, and JavaScript game where you control a green square using your keyboard. Let’s dive in!

The Canvas: Your Game World

The game uses the HTML canvas element as the playing field. This is where all the action happens: drawing, moving, and updating the player square.

Player Representation & Movement

The player is a simple green square, but the magic lies in how you control it! Using JavaScript, we listen for arrow key presses and update the player’s position smoothly, creating a responsive and fun experience.

Game Constants & Initial State

// --- Game Constants ---
const CANVAS_SIZE = 400; // Canvas width and height (square)
const PLAYER_SIZE = 40; // Player size in pixels
const PLAYER_COLOR = '#4caf50'; // Player color
const PLAYER_RADIUS = 8; // Corner radius for rounded player
const MOVE_STEP = 4; // Pixels moved per frame when key is held

// --- Player State ---
let playerX = 180; // Initial X position
let playerY = 180; // Initial Y position

// --- Keyboard State ---
const keysPressed = {
  ArrowUp: false,
  ArrowDown: false,
  ArrowLeft: false,
  ArrowRight: false
};
  • Arrow keys: Move the player up, down, left, or right.
  • Continuous motion: Holding a key keeps the player moving, thanks to the game loop.

The Game Loop

At the heart of the game is the game loop, a function that runs many times per second, updating the player’s position and redrawing the canvas. This ensures smooth animations and real-time feedback.

 
// --- Main Game Loop ---
function gameLoop() {
  // Clear the canvas for the new frame
  ctx.clearRect(0, 0, CANVAS_SIZE, CANVAS_SIZE);

  // Update player position based on input
  movePlayer();

  // Draw the player at the new position
  drawPlayer();

  // Request the next frame
  requestAnimationFrame(gameLoop);
}

Handling Keyboard Input

We use event listeners to track key presses, allowing for smooth and responsive movement.

// --- Keyboard Event Listeners ---
document.addEventListener('keydown', (event) => {
  if (event.key in keysPressed) {
    keysPressed[event.key] = true;
  }
});

document.addEventListener('keyup', (event) => {
  if (event.key in keysPressed) {
    keysPressed[event.key] = false;
  }
});

Drawing the Player

While games often use image sprites for characters, this tutorial keeps it simple by drawing the player directly using the CanvasRenderingContext2D API. The player is rendered as a green rounded square with smooth corners.

// --- Draw the Player (Green Rounded Square) ---
function drawPlayer() {
  ctx.fillStyle = PLAYER_COLOR;
  ctx.beginPath();
  ctx.moveTo(playerX + PLAYER_RADIUS, playerY);
  ctx.lineTo(playerX + PLAYER_SIZE - PLAYER_RADIUS, playerY);
  ctx.quadraticCurveTo(playerX + PLAYER_SIZE, playerY, playerX + PLAYER_SIZE, playerY + PLAYER_RADIUS);
  ctx.lineTo(playerX + PLAYER_SIZE, playerY + PLAYER_SIZE - PLAYER_RADIUS);
  ctx.quadraticCurveTo(playerX + PLAYER_SIZE, playerY + PLAYER_SIZE, playerX + PLAYER_SIZE - PLAYER_RADIUS, playerY + PLAYER_SIZE);
  ctx.lineTo(playerX + PLAYER_RADIUS, playerY + PLAYER_SIZE);
  ctx.quadraticCurveTo(playerX, playerY + PLAYER_SIZE, playerX, playerY + PLAYER_SIZE - PLAYER_RADIUS);
  ctx.lineTo(playerX, playerY + PLAYER_RADIUS);
  ctx.quadraticCurveTo(playerX, playerY, playerX + PLAYER_RADIUS, playerY);
  ctx.closePath();
  ctx.fill();
}

Updating the Player’s Position

The movePlayer() function calculates the new position based on key presses and keeps the player inside the canvas.

// --- Update Player Position Based on Key State ---
function movePlayer() {
  let dx = 0;
  let dy = 0;

  if (keysPressed.ArrowUp) dy -= MOVE_STEP;
  if (keysPressed.ArrowDown) dy += MOVE_STEP;
  if (keysPressed.ArrowLeft) dx -= MOVE_STEP;
  if (keysPressed.ArrowRight) dx += MOVE_STEP;

  // Clamp position so player stays inside canvas
  playerX = Math.max(0, Math.min(CANVAS_SIZE - PLAYER_SIZE, playerX + dx));
  playerY = Math.max(0, Math.min(CANVAS_SIZE - PLAYER_SIZE, playerY + dy));
}

Putting It All Together

Finally, we start the game by calling gameLoop():

// --- Start the Game ---
gameLoop();

How to Make It Your Own ✨

Want to add new features? Try:

  • Changing the player’s appearance

  • Adding obstacles

  • Keeping score!

This project is a perfect starting point for learning or prototyping your own browser games.

Want to Try It Yourself?

Explore the full code & customize it!
This project is part of my Basic Game Scaffold repo, a minimalist template to kickstart your own browser-based games.

What’s inside?

  • Clean HTML/CSS/JS structure

  • Modular code for easy expansion

  • Perfect for beginners or quick prototypes

Clone, tweak, and build something awesome!

⭐️ Feel free to use or modify this project for your own creations. Happy coding!

Back to Posts