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:
We will use our last example, listening to multiple keyboard inputs, as the starting point.
Open the
js/pingpong.js
file in the text editor.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()), },
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 } }
We define a
gameloop
function and...