官术网_书友最值得收藏!

Time for action – auto moving the left paddle

Perform the following set of actions for automoving our paddle:

  1. Let's continue with our pingpong.js JavaScript file. We create a function that follows the ball's y position.
    function autoMovePaddleA() {
      var speed = 4;
      var direction = 1;
    
      var paddleY = pingpong.paddleA.y + pingpong.paddleA.height/2;
      if (paddleY > pingpong.ball.y) {
        direction = -1;
      }
    
      pingpong.paddleA.y += speed * direction;
    }
  2. Then, inside the game loop function, we call our autoMovePaddleA function.
    autoMovePaddleA();

What just happened?

We created a logic that moves the left paddle based on the ball's y position. You may try the game with its current progress at http://makzan.net/html5-games/pingpong-wip-step6/.

Since we have already implemented the view rendering in the renderPaddles function, in this section, we only need to update the paddle's data and the view will get updated automatically.

We make the paddle speed slower than the ball's speed. Otherwise, the player can never win against the computer, because the computer-controlled paddle can always catch the ball and bounce it back if they have the same speed.

主站蜘蛛池模板: 普安县| 平安县| 仁化县| 花莲县| 交口县| 龙海市| 吉首市| 安溪县| 辽宁省| 皮山县| 漾濞| 张家界市| 文昌市| 麦盖提县| 潼关县| 华安县| 东安县| 青龙| 白城市| 南阳市| 房产| 大田县| 伊吾县| 习水县| 大竹县| 奉节县| 琼结县| 武胜县| 宝丰县| 眉山市| 武功县| 江孜县| 隆安县| 耒阳市| 繁峙县| 南投县| 汉中市| 昌图县| 秦皇岛市| 古交市| 密云县|