atari突破游戏球虫?

时间:2017-02-13 16:37:34

标签: javascript

我目前正在构建一个非常简化的Atari突破游戏版本。在运行这段代码约5秒后(在球围绕棋盘围绕3圈之后),球被卡在右壁并进行奇怪的抖动跳跃运动。当我改变球或板或任何其他元素的宽度/高度属性时,它工作正常。我很困惑为什么会发生这种情况。这是代码:

<!DOCTYPE html>
<html>
<head>
  <meta charset='utf-8'>
  <title>Atari Breakout</title>
  <link rel='stylesheet' href='breakout.css'>
</head>
<body>
  <canvas id='myCanvas' width='480' height='320'></canvas>

  <script>
  var canvas = document.getElementById("myCanvas");
  var ctx = canvas.getContext("2d");

  var x = canvas.width/2;
  var y = canvas.height-30;
  var dx = 2;
  var dy = -2;
  var ballRadius = 10;

  function drawBall() {
    ctx.beginPath()
    ctx.arc(x, y, ballRadius, 0 , Math.PI*2);
    ctx.fillStyle = "rgba(0, 0, 255, 0.8)";
    ctx.fill();
    ctx.closePath();
  }
  function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    drawBall();
    drawPaddle();
    x += dx;
    y += dy;
    if ((y + dy < ballRadius) || (y + dy > canvas.height - ballRadius)) {
      dy = -dy;
    }

    if ((x + dx < ballRadius) || (x + dy > canvas.width - ballRadius)) {
      dx = -dx;
    }
  }

  setInterval(draw, 10);

</script>
</body>
</html>

代码不干净,但我不明白为什么球在大约6秒后卡在右墙上?

0 个答案:

没有答案