<html>
  <head>
    <title>Platformer</title>
    <style>
      canvas {
        border: 1px solid #d3d3d3;
        background-color: #f1f1f1;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="400" height="400"></canvas>
<pre><code>&lt;script&gt;
  // Get the canvas element
  var canvas = document.getElementById('myCanvas');
  // Get the context element which is used to draw on the canvas
  var ctx = canvas.getContext('2d');

  // Set the position of the player
  var x = canvas.width / 2;
  var y = canvas.height - 30;

  // Set the size of the player
  var playerWidth = 20;
  var playerHeight = 20;

  // Set the speed of the player
  var speedX = 2;
  var speedY = -2;

  // Set the position of the obstacles
  var obstacleX = canvas.width / 2;
  var obstacleY = canvas.height - 30;

  // Set the size of the obstacle
  var obstacleWidth = 20;
  var obstacleHeight = 20;

  // Draw the player
  function drawPlayer() {
    ctx.beginPath();
    ctx.rect(x, y, playerWidth, playerHeight);
    ctx.fillStyle = '#0095DD';
    ctx.fill();
    ctx.closePath();
  }

  // Draw the obstacle
  function drawObstacle() {
    ctx.beginPath();
    ctx.rect(obstacleX, obstacleY, obstacleWidth, obstacleHeight);
    ctx.fillStyle = '#0095DD';
    ctx.fill();
    ctx.closePath();
  }

  // Move the player and the obstacle
  function movePlayer() {
    x += speedX;
    y += speedY;
    obstacleX -= speedX;
    obstacleY -= speedY;

    if (x + playerWidth &gt; canvas.width || x &lt; 0) {
        speedX = -speedX;
    }
    if (y + playerHeight &gt; canvas.height || y &lt; 0) {
        speedY = -speedY;
    }
    if (obstacleX + obstacleWidth &gt; canvas.width || obstacleX &lt; 0) {
        speedX = -speedX;
    }
    if (obstacleY + obstacleHeight &gt; canvas.height || obstacleY &lt; 0) {
        speedY = -speedY;
    }
  }

  // Check for player collisions with the obstacle
  function checkCollision() {
    if (x &lt; obstacleX + obstacleWidth &amp;&amp;
       x + playerWidth &gt; obstacleX &amp;&amp;
       y &lt; obstacleY + obstacleHeight &amp;&amp;
       y + playerHeight &gt; obstacleY) {
        alert('Game Over!');
        document.location.reload();
    }
  }

  // Draw everything
  function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    drawPlayer();
    drawObstacle();
    movePlayer();
    checkCollision();
    requestAnimationFrame(draw);
  }

  draw();
&lt;/script&gt;
</code></pre>
  </body>
</html>
HTML Platform Game Code Example - Learn to Build a Basic Platformer

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

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