javascript:pong游戏不会从底部屏幕反弹

时间:2017-02-04 18:37:15

标签: javascript pong

我创造了一个乒乓球游戏,我到达了球从三个墙壁反弹的点,但当我试图让它从底壁反弹时,它只是越过它,然后像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>

1 个答案:

答案 0 :(得分:1)

:${#line}函数中有一个小错字:

move

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