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

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.

主站蜘蛛池模板: 务川| 芦山县| 夹江县| 亳州市| 五莲县| 鲜城| 汨罗市| 永城市| 特克斯县| 东乌珠穆沁旗| 南涧| 宁国市| 达拉特旗| 巴彦淖尔市| 佛坪县| 黄冈市| 塔河县| 汝城县| 离岛区| 罗城| 泽州县| 滁州市| 连南| 株洲县| 宜兴市| 班戈县| 泰顺县| 四会市| 云和县| 乐都县| 大同县| 天津市| 基隆市| 博乐市| 安宁市| 宾阳县| 改则县| 信阳市| 双牌县| 溧水县| 赤城县|