<!DOCTYPE html>
<html>
  <body>
    <canvas id='canvas' width='500' height='370' style='border:1px solid #000000;'></canvas>
    <script>
      // canvas variables
      var canvas = document.getElementById('canvas');
      var ctx = canvas.getContext('2d');
      var x = canvas.width/2;
      var y = canvas.height-30;
      var dx = 2;
      var dy = -2;
      var ballRadius = 10;
<pre><code>  // platform variables
  var platformHeight = 10;
  var platformWidth = 75;
  var platformX = (canvas.width - platformWidth)/2;

  // draw the ball
  function drawBall(){
    ctx.beginPath();
    ctx.arc(x, y, ballRadius, 0, Math.PI*2);
    ctx.fillStyle = '#0095DD';
    ctx.fill();
    ctx.closePath();
  }

  // draw the platform
  function drawPlatform(){
    ctx.beginPath();
    ctx.rect(platformX, canvas.height-platformHeight, platformWidth, platformHeight);
    ctx.fillStyle = '#0095DD';
    ctx.fill();
    ctx.closePath();
  }

  // draw function
  function draw(){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    drawBall();
    drawPlatform();
    x += dx;
    y += dy;
    // check for wall collisions
    if(x + dx &gt; canvas.width-ballRadius || x + dx &lt; ballRadius){
      dx = -dx;
    }
    // check for platform collisions
    if(y + dy &lt; ballRadius) {
      dy = -dy;
    } else if (y + dy &gt; canvas.height-ballRadius) {
      // check if the ball is hitting the platform
      if(x &gt; platformX &amp;&amp; x &lt; platformX + platformWidth){
        dy = -dy;
      }
      else {
        alert('GAME OVER');
        document.location.reload();
      }
    }
  }
  // call draw function every 10ms
  setInterval(draw, 10);
&lt;/script&gt;
</code></pre>
  </body>
</html>
Simple HTML Platformer Game - Build Your First Game Now!

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

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