javascript: 乒乓球游戏不会从底部屏幕弹回

javascript: pong game won't bounce off the bottom screen

我正在创建一个乒乓球游戏,我到达了球从三堵墙反弹的地步,但是当我试图让它从底墙反弹时,它只是越过它然后大约 5 秒后它回来

<canvas id="pg" width = "800" height = "600">
  <script>
    var c;
    var cc;
    var ballx = 50;
    var ballY = 50;
    var ballSpeedX = 1.5;
    var ballSpeedY = 4;

    window.onload = function(){
      c = document.getElementById("pg");
      cc = c.getContext("2d");

      var fps = 180;
      setInterval(function(){
        move();
        draw();
      },1000/fps)
    }

    function move(){
      ballx += ballSpeedX
      if(ballx < 0) {
        ballSpeedX = -ballSpeedX;
      }
      if(ballx > c.width) {
        ballSpeedX = -ballSpeedX;
      }
      ballY += ballSpeedY
      if(ballY < 0) {
        ballSpeedY = -ballSpeedY;
      }
      if(ballx > c.height) {
        ballSpeedY = -ballSpeedY;
      }

    }
    function draw(){
      colorRect(0,0,c.width,c.height,"black");
      colorRect(10,210,5,100,"white");
      colorCircle(ballx,ballY,10,"white")

    }
    function colorCircle(centerX, centerY, radius, drawColor){
      cc.fillStyle = drawColor
      cc.beginPath();
      cc.arc(centerX, centerY,5,0,Math.PI*2,true);
      cc.fill();
    }
    function colorRect(leftX,topY,width,height,drawColor){
      cc.fillStyle = drawColor;
      cc.fillRect(leftX,topY,width,height);
    }
  </script>
</canvas>

您的 move 函数中有一个小错别字:

// The last if should check if ballY > c.height instead
if(ballx > c.height) {
    ballSpeedY = -ballSpeedY;
}

<canvas id="pg" width = "800" height = "600">
  <script>
    var c;
    var cc;
    var ballx = 50;
    var ballY = 50;
    var ballSpeedX = 1.5;
    var ballSpeedY = 4;

    window.onload = function(){
      c = document.getElementById("pg");
      cc = c.getContext("2d");

      var fps = 180;
      setInterval(function(){
        move();
        draw();
      },1000/fps)
    }

    function move(){
      ballx += ballSpeedX
      if(ballx < 0) {
        ballSpeedX = -ballSpeedX;
      }
      if(ballx > c.width) {
        ballSpeedX = -ballSpeedX;
      }
      ballY += ballSpeedY
      if(ballY < 0) {
        ballSpeedY = -ballSpeedY;
      }
      if(ballY > c.height) {
        ballSpeedY = -ballSpeedY;
      }

    }
    function draw(){
      colorRect(0,0,c.width,c.height,"black");
      colorRect(10,210,5,100,"white");
      colorCircle(ballx,ballY,10,"white")

    }
    function colorCircle(centerX, centerY, radius, drawColor){
      cc.fillStyle = drawColor
      cc.beginPath();
      cc.arc(centerX, centerY,5,0,Math.PI*2,true);
      cc.fill();
    }
    function colorRect(leftX,topY,width,height,drawColor){
      cc.fillStyle = drawColor;
      cc.fillRect(leftX,topY,width,height);
    }
  </script>
</canvas>