Build your own indie HTML5 game: platformer

Building a platformer game in HTML5 requires a combination of HTML, CSS, and JavaScript.

You can easily create your own HTML5 indie game in a few hours

Here’s a step-by-step guide with code examples:

Create an HTML file and add a canvas element to it, which will be used to draw the game graphics.

<!DOCTYPE html>
<html>
  <head>
    <title>Platformer Game</title>
    <style>
      canvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="800" height="600"></canvas>
    <script src="game.js"></script>
  </body>
</html>

Create a JavaScript file and add it to the HTML file using the script tag. This file will contain the game logic.

const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

// Define player properties
let player = {
  x: 50,
  y: 50,
  width: 50,
  height: 50,
  speed: 5,
  jumping: false,
};

// Draw the player on the canvas
function drawPlayer() {
  ctx.fillStyle = "blue";
  ctx.fillRect(player.x, player.y, player.width, player.height);
}

// Move the player
function movePlayer() {
  if (rightPressed && player.x < canvas.width - player.width) {
    player.x += player.speed;
  } else if (leftPressed && player.x > 0) {
    player.x -= player.speed;
  }

  if (jumpPressed && !player.jumping) {
    player.jumping = true;
    player.yVelocity = -player.speed * 2;
  }

  if (player.jumping) {
    player.yVelocity += 0.2;
    player.y += player.yVelocity;

    if (player.y > canvas.height - player.height) {
      player.jumping = false;
      player.y = canvas.height - player.height;
      player.yVelocity = 0;
    }
  }
}

// Game loop
function gameLoop() {
  // Clear the canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Draw the player
  drawPlayer();

  // Move the player
  movePlayer();

  // Call gameLoop again
  requestAnimationFrame(gameLoop);
}

// Start the game loop
requestAnimationFrame(gameLoop);

Define keyboard controls for the player. This is done by adding event listeners to the document object.

let rightPressed = false;
let leftPressed = false;
let jumpPressed = false;

document.addEventListener("keydown", (event) => {
  if (event.code === "ArrowRight") {
    rightPressed = true;
  } else if (event.code === "ArrowLeft") {
    leftPressed = true;
  } else if (event.code === "Space") {
    jumpPressed = true;
  }
});

document.addEventListener("keyup", (event) => {
  if (event.code === "ArrowRight") {
    rightPressed = false;
  } else if (event.code === "ArrowLeft") {
    leftPressed = false;
  } else if (event.code === "Space") {
    jumpPressed = false;
  }
});

Add platforms to the game. This can be done by creating an array of platform objects and drawing them on the canvas.

let platforms = [
  {
    x: 0,
    y: 550,
    width: 800,
    height: 50,
  },
  {
    x: 300,
    y: 400,
    width: 200,
    height: 25,
  },
];

// Draw platforms on the canvas
function drawPlatforms() {
  ctx.fillStyle = "green";
  platforms.forEach((platform) => {
    ctx.fillRect(platform.x, platform.y, platform.width, platform.height);
  });
}

Add collision detection between the player and platforms. This can be done by checking if the player’s coordinates overlap with the platform’s coordinates.

function checkCollision(player, platform) {
  let bottom = player.y + player.height >= platform.y;
  let top = player.y <= platform.y + platform.height;
  let right = player.x + player.width >= platform.x;
  let left = player.x <= platform.x + platform.width;

  return bottom && top && right && left;
}

function handleCollision() {
  platforms.forEach((platform) => {
    if (checkCollision(player, platform)) {
      if (player.yVelocity > 0) {
        player.jumping = false;
        player.y = platform.y - player.height;
        player.yVelocity = 0;
      } else if (player.yVelocity < 0) {
        player.y = platform.y + platform.height;
        player.yVelocity = 0;
      }
    }
  });
}

Add enemies to the game. This can be done by creating an array of enemy objects and drawing them on the canvas.

let enemies = [
  {
    x: 700,
    y: 500,
    width: 50,
    height: 50,
    speed: 3,
    direction: "left",
  },
];

// Draw enemies on the canvas
function drawEnemies() {
  ctx.fillStyle = "red";
  enemies.forEach((enemy) => {
    ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);
  });
}

Add collision detection between the player and enemies. This can be done using the same checkCollision function as before.

function checkEnemyCollision(player, enemy) {
  let bottom = player.y + player.height >= enemy.y;
  let top = player.y <= enemy.y + enemy.height;
  let right = player.x + player.width >= enemy.x;
  let left = player.x <= enemy.x + enemy.width;

  return bottom && top && right && left;
}

function handleEnemyCollision() {
  enemies.forEach((enemy) => {
    if (checkEnemyCollision(player, enemy)) {
      // Game over
      console.log("Game over");
    }
  });
}

Add scoring to the game. This can be done by incrementing a score variable whenever the player reaches a certain point on the canvas.

let score = 0;
let scoreThreshold = 700;

function handleScore() {
  if (player.x > scoreThreshold) {
    score += 10;
    scoreThreshold += 700;
  }

  ctx.font = "20px Arial";
  ctx.fillStyle = "black";
  ctx.fillText(`Score: ${score}`, 10, 30);
}

Add a game over screen when the player collides with an enemy. This can be done by stopping the game loop and displaying a message on the canvas.

function gameOver() {
  cancelAnimationFrame(animationId);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.font = "50px Arial";
  ctx.fillStyle = "red";
  ctx.textAlign = "center";
  ctx.fillText("Game Over", canvas.width / 2, canvas.height / 2);
}

function gameLoop() {
  // Clear the canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Draw the player
  drawPlayer();

  // Move the player
  movePlayer();

  // Draw platforms on the canvas
  drawPlatforms();

  // Handle collisions between the player and platforms
  handleCollision();

  // Draw enemies on the canvas
  drawEnemies();

  // Handle collisions between the player and enemies
  handleEnemyCollision();

  // Handle the score
  handleScore();

  // Check if the player is off-screen
  if (player.y > canvas.height) {
    gameOver();
    return;
  }

  // Call gameLoop again
  animationId = requestAnimationFrame(gameLoop);
}

// Start the game loop
let animationId = requestAnimationFrame(gameLoop);

Finally, add some finishing touches to the game, such as background music, sound effects, and a start screen.

let audio = new Audio("background_music.mp3");
audio.loop = true;
audio.play();

let jumpSound = new Audio("jump_sound.mp3");
let collisionSound = new Audio("collision_sound.mp3");

document.addEventListener("keydown", (event) => {
  if (event.code === "KeyM") {
    audio.paused ? audio.play() : audio.pause();
  }
});

ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.font = "50px Arial";
ctx.fillStyle = "black";
ctx.textAlign = "center";
ctx.fillText("Press Space to Start", canvas.width / 2, canvas.height / 2);

document.addEventListener("keydown", (event) => {
  if (event.code === "Space") {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    animationId = requestAnimationFrame(gameLoop);
  }
});

And that’s it! This is a basic example of how to create a platformer game in HTML5. You can customize and add more features to this game as per your requirement.

author avatar
Fungies
Fungies.io helps game developers create their own storefronts or marketplaces to sell directly to players. Web2 and Web3 compatible.

 

Fungies.io helps game developers create their own storefronts or marketplaces to sell directly to players. Web2 and Web3 compatible.

Post a comment

Your email address will not be published. Required fields are marked *