Lesson 10: Animating with a Game Loop
In the last lesson you set up a gameloop function that runs every one second. Now you are ready to use that Game Loop to animate an image across the screen.
1. Add the following code into gameloop.
The variable y (commonly used for the vertical location of an element) is declared inside gameloop so can only be used within this function. The variable monkey_01 was declared outside of any function so may be used anywhere. You are setting y to equal the monkey_01's vertical position. The output variable (which was set equal to the output div) in the init() is being used to display the value of y.
You can see that the value of y is not a number. Instead, because of the "px" at the end, it is a String that includes numbers and characters. You need this to be a number so that you can do mathematical operations with it.
2. Use the parseInt() function to convert the String to an integer.
3. Now that y is an integer (there is no "px" displayed), you can subtract to reduce it's value.
Every time gameloop runs, the value of y is recalculated. However, since you never change the top value of monkey_01, y is always equal to 255.
4. You need to change the top value of monkey_01 to equal the new y value you calculated, which is always 5 less than its current value. Each time gameloop runs, the actual vertical position of monkey_01 should decrease.
Eureka! You have animation!
5. You are done with the output div for now, so comment out or delete the code.
Unfortunately, this is very choppy animation. You want our animation to be as smooth as butter.
Animation is actually created by a series of images, or frames. If you can show at least 12 frames per second (FPS), the illusion of motion will be achieved. Movies in the film industry use 24 FPS.
6. By changing the interval time in the setInterval function to 50, gameloop will be called 20 times per second (50x20=1000). You don't want to increase your frame rate over 20 FPS because running the code in gameloop more frequently than needed can cause performance problems, especially when there is alot of code to be executed.
You probably are noticing that changing the interval time of setInterval changes the speed at which the animation occurs. Don't do this... choose the lowest frame rate that effectively achieves the illusion of motion. I am going to leave my interval time set to run the gameloop every 50 milliseconds (20 FPS). To change the speed of the objects being animated, just change the amount the y value is being decreased by.
That should speed things up.
Test Yourself!
setInterval(mainloop, 100);
if elements are moved in the mainloop() function, what would be the resulting frames per second?