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 – Moving the ball with JavaScript Interval


We will use the function to create a timer. The timer moves the ball a little bit every 30 milliseconds. We are going to also change the direction of the ball movement once it hits the playground edge. Let's make the ball move now:

  1. We will use our last example, listening to multiple keyboard inputs, as the starting point.

  2. Open the js/pingpong.js file in the text editor.

  3. In the existing pingpong.playground object, we change to the following code that adds height and width to the playground.

    playground: {
      offsetTop: $("#playground").offset().top,
      height: parseInt($("#playground").height()),
      width: parseInt($("#playground").width()),
    },
  4. We are now moving the ball, and we need to store the ball's status globally. We will put the ball-related variable inside the pingpong object:

    var pingpong = {
      //existing data
      ball: {
        speed: 5,
        x: 150,
        y: 100,
        directionX: 1,
        directionY: 1
      }
    }
  5. We define a gameloop function and...