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

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.

主站蜘蛛池模板: 城固县| 商都县| 探索| 稷山县| 成都市| 如皋市| 屏边| 蒲江县| 大厂| 响水县| 五华县| 沁源县| 宜黄县| 健康| 甘谷县| 许昌市| 甘谷县| 南和县| 南丰县| 耒阳市| 乳源| 龙井市| 新丰县| 乃东县| 渭南市| 和田县| 定边县| 砚山县| 阆中市| 鸡东县| 鹰潭市| 怀安县| 黔西| 定日县| 莲花县| 双城市| 孟连| 扎囊县| 阜阳市| 财经| 湘乡市|