Time and Animation
The execTm function returns the execution time of the program.
While the program is running, try pressing the 'Pause' button to observe how it affects the execution time.
This program draws a disc moving at a speed of 100 pixels per second.
The screen image might be unstable. This happens because the computer will sometimes refresh the screen before the program has finished drawing the image.
If, for demonstrational purposes, the screen image is not sufficiently unstable , try decreasing the argument of the sleepMs function to value 0.03.
Here is an improved version of the program with a stable image.
The vsync function waits for the computer to finish refreshing the screen. The computer refreshes the screen at the display device's frame rate.
After the vsync function completes, the program can draw to the screen again.
* * *
-- Vertical Synchronization --
The vertical synchronization signal is issued by the graphics processing unit (GPU) when it has completed sending the contents of the display framebuffer to the display device. The vsync function is similar to the sleepMs function, except that it pauses the program until the vertical synchronization signal is received from the GPU.
This program calculates and displays the time elapsed between two animation frames.
An animation frame is one complete image drawn to the computer screen.
This program draws one animation frame on each iteration of the while loop.
The elapsed time varies on different computers and display devices. It is usually in the range of 8–50 milliseconds (0.008 – 0.050 seconds), corresponding to the frame rates of 20-125 Hz.
Here is a program that moves a ball left and right according to the presses of the arrow keys.
The speed of the ball is the same on any computer running this program, and equals 300 pixels per second.
This program can move the ball in all directions.
Instead of making the arrow keys change ball's position, this program makes them change ball's velocity.
The variables vx and vy together make a motion vector. The motion vector determines the velocity of the ball.
Don't lose the ball out off the screen!
Here is a simulation of a bouncing ball.
Press left and right arrow keys to move the ball.
Here is another simulation of a bouncing ball.
It is easy to make the ball jump higher, but it is very hard to make it steady.