<!DOCTYPE html>
<html>
<head>
  <title>Platformer Game</title>
  <style>
    #game {
      width: 800px;
      height: 600px;
      background-color: #ccc;
      margin: 0 auto;
    }
<pre><code>.player {
  width: 50px;
  height: 50px;
  background-color: #000;
  position: relative;
}

.platform {
  width: 200px;
  height: 40px;
  background-color: #444;
  position: absolute;
}
</code></pre>
  </style>
</head>
<body>
  <div id='game'>
    <div class='player'></div>
    <div class='platform'></div>
  </div>
  <script>
    var game = document.getElementById('game');
    var player = document.querySelector('.player');
    var platform = document.querySelector('.platform');
    var gravity = 0.7;
    var isJumping = false;
<pre><code>// Move the platform
function movePlatform() {
  platform.style.left = Math.random() * (game.offsetWidth - platform.offsetWidth) + 'px';
}

// Move the player
function movePlayer() {
  // Move left
  if (isLeftKey) {
    player.style.left = player.offsetLeft - 5 + 'px';
  }
  // Move right
  if (isRightKey) {
    player.style.left = player.offsetLeft + 5 + 'px';
  }
  // Jump
  if (isSpaceKey &amp;&amp; !isJumping) {
    isJumping = true;
    jumpVelocity = -25;
  }
  // Gravity
  if (player.offsetTop &lt; (game.offsetHeight - player.offsetHeight)) {
    jumpVelocity += gravity;
    player.style.top = player.offsetTop + jumpVelocity + 'px';
  } else {
    isJumping = false;
  }
}

// Keyboard events
var isLeftKey = false;
var isRightKey = false;
var isSpaceKey = false;

document.addEventListener('keydown', function(e) {
  if (e.keyCode === 37) {
    isLeftKey = true;
  } else if (e.keyCode === 39) {
    isRightKey = true;
  } else if (e.keyCode === 32) {
    isSpaceKey = true;
  }
});

document.addEventListener('keyup', function(e) {
  if (e.keyCode === 37) {
    isLeftKey = false;
  } else if (e.keyCode === 39) {
    isRightKey = false;
  } else if (e.keyCode === 32) {
    isSpaceKey = false;
  }
});

// Main loop
function loop() {
  movePlatform();
  movePlayer();
  requestAnimationFrame(loop);
}

loop();
</code></pre>
  </script>
</body>
</html>
HTML Platform Game Code - Create Your Own Jump and Run Game

原文地址: https://www.cveoy.top/t/topic/lnR2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录