bigbadbrain logo
bbb Home
  Lesson 4 - Animation - Move Ball
 

SUMMARY

In this lesson we will add code to randomly set the location of the ball and begin its movement.  This lesson will use concepts learned in previous lessons.

DISCUSSION

When the game begins we will move the ball to a random location so that the game is different each time we play.  We will set the position of the ball using the Math.random() function which we used in previous lessons.  We will then start a timer.  Everytime the timer ticks we will move the ball.   The appearance of the animation is determined by how frequently we move the ball and how far we move it each time the timer ticks.  We will start a timer using window.setInterval.  Each time the timer ticks we will call a function to add some small amount to the location of the ball. 

The example illustrates how to animate an object.  Load the code and then click on the page.  The <div> will move across the screen.  The <div> moves because each time the timer ticks we add 10 to the left position of the <div>.  In the example, we keep track of the location of the variable px. We add 10 to px each time the timer ticks and then we set the left position of the <div> to px.
 

EXAMPLE - Animation

 Font Size: 10pt 12pt   View Large Version
 Ctrl-C to Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

PRACTICE

1.  Experiment with the code above by changing the frequency that the timer ticks and the amount the <div> is moved.  What combination of these two values makes the animation smooth?  
 
2.  Modify the code to move the <div> in the vertical direction along with the horizontal direction.

3.   Create a page with an image at position 0,0. When the user presses the "a" key the image should begin to move diagonally down the page.

4.  Modify your page in #3 so that the image moves to a random location when the user clicks on it.

GAME DEVELOPMENT

1.  Modify your game page so that the ball is set to a random location and the ball begins to move when the user clicks a key to start the game.  In the next lesson we will make the ball move in a random direction when the game starts.
©dfx interactive, inc. Contact us at bigbadbrain@bigbadbrain.com