7 min read
🎮beginner

Sprite Movement — Making Characters Move

Learn how to move game characters on screen using coordinates, velocity, and keyboard input in JavaScript.

What is a Sprite?

In game development, a 'sprite' is any visual object in your game — a character, an enemy, a bullet, a coin, a platform. It is basically an image with a position on screen. Every sprite has at least two properties: an x position (how far from the left) and a y position (how far from the top). To move a sprite, you just change its x or y value each frame. Remember: in screen coordinates, x increases going RIGHT and y increases going DOWN (not up!). This confuses many beginners.

Moving a Square with Arrow Keys

javascript
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');

// Our player sprite
let player = {
  x: 200,
  y: 200,
  width: 40,
  height: 40,
  speed: 5,
  color: '#00ff88'
};

// Track which keys are pressed
let keys = {};
window.addEventListener('keydown', (e) => keys[e.key] = true);
window.addEventListener('keyup', (e) => keys[e.key] = false);

function gameLoop() {
  // UPDATE - Move player based on keys
  if (keys['ArrowUp']) player.y -= player.speed;
  if (keys['ArrowDown']) player.y += player.speed;
  if (keys['ArrowLeft']) player.x -= player.speed;
  if (keys['ArrowRight']) player.x += player.speed;

  // RENDER - Clear screen and draw player
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = player.color;
  ctx.fillRect(player.x, player.y, player.width, player.height);

  requestAnimationFrame(gameLoop);
}
gameLoop();

Smooth Movement with Velocity

In the example above, the player moves at a fixed speed. But real games often use velocity — the sprite has a speed that can change over time. Instead of moving directly, you add velocity each frame: - Player presses right arrow: velocity.x += acceleration - Each frame: player.x += velocity.x - When they let go: gradually reduce velocity (friction) This creates much smoother, more natural-feeling movement. It is the difference between a character that feels like a robot and one that feels alive.
Pro Tip

Always add boundary checking to keep your sprite on screen! Without it, the player can move off the edge and disappear. A simple check: if (player.x < 0) player.x = 0; if (player.x + player.width > canvas.width) player.x = canvas.width - player.width; Do the same for y.

Make It Move

Create an HTML file with a canvas element and use the code above to make a colored square you can move with arrow keys. Then try these upgrades: 1) Add boundary checking so the square cannot leave the screen. 2) Change the color of the square each time it reaches an edge. 3) Add a second square controlled by WASD keys (W for up, A for left, S for down, D for right). Now you have a two-player game!

Ready to build?

Put what you learned into practice — pick a project and start coding.

Start Building Free