How can I use JS to make a platformer?

I want to use JS to create a side scrolling platformer with double-jump. Also, when you click up, the player will jump. Jump with up arrow key or w.

https://replit.com/@BluebayStudios/bluebaysonlyup

You need to add a canvas to your html and build the javascript. The JS will handle user input and the physics of jumping.

The HTML will be something like this:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Platformer Game</title>
  <style>
    body {
      margin: 0;
    }
    canvas {
      background: #f0f0f0;
      display: block;
      margin: auto;
    }
  </style>
</head>
<body>
  <canvas id="gameCanvas" width="800" height="400"></canvas>
  <script src="script.js"></script>
</body>
</html>

The JavaScript goes to setting up your game loop, handle the keyboard input, define the player and the functions.

For example you can use a EventListener to handle the keyboard

let keys = {};

window.addEventListener('keydown', function(e) {
  keys[e.key] = true;
});

window.addEventListener('keyup', function(e) {
  keys[e.key] = false;
});
1 Like

How can I add side-scrolling and double-jump?

The double jump you can set an event for when the player presses ‘w’ or the up arrow key and player.isJumping is false (meaning the player is on the ground), to make him move up the screen (first jump).

And then, if the player presses ‘w’ or the up arrow key again while player.isJumping is true (meaning they are already in the air from the first jump), it creates the double jump.

For example:

if ((keys['w'] || keys['ArrowUp']) && !player.isJumping) {
  player.vy = player.jumpPower; // First jump
  player.isJumping = true;
} else if ((keys['w'] || keys['ArrowUp']) && player.isJumping && !player.doubleJumped) {
  player.vy = player.doubleJumpPower; // Second jump
  player.doubleJumped = true;
}

About the side scrolling that’s a bit more complicated… but you can find easy guides online.

Something you don’t understand @boston2029 ?

1 Like

Well, I was gonna say that you could just make a <div> and use position: absolute; and top and left to move the div, but using a canvas is probably more efficient. [1]


  1. This is what I would have done at first thought honestly. ↩︎

In this case I think canvas is better since the scene changes frequently (considering the type of game he wants).

In my mind he seems to want something more complex and a smooth animation, but if it were more simple I would totally go with the <div>.