Book Image

HTML5 Game Development by Example: Beginner's Guide

By : Seng Hin Mak
Book Image

HTML5 Game Development by Example: Beginner's Guide

By: Seng Hin Mak

Overview of this book

Table of Contents (18 chapters)
HTML5 Game Development by Example Beginner's Guide Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
9
Building a Physics Car Game with Box2D and Canvas
Index

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...