Programming Course for Beginners - ZedLX

The Easiest Online Computer Programming Course, for Free

The type vector2D [8/11]

This program is a small improvement over the previous program. It uses the function vsync to create a smooth animation. When the vsync function is employed, the elapsed time between animation frames needs to be accounted for.
[Run the program]

The vector velocity represents the balls's speed and direction. The initial velocity is 20 pixels per second to the leftwards and 50 pixels per second downwards.

The point position represents the balls's current position.

On each display frame, the position of the ball is updated according to the rule of motion vectors. The rule is implemented in the penultimate statement of the main loop:
position = position.add(velocity * elapsedTime);
This statement changes position of the ball by adding a motion vector to the point position. The position must be moved by farther when the elapsed time between two frames is greater. Therefore, the vector velocity must first be scaled by the elapsedTime, before being added to the position.

Exercises:

1. In the source code, uncomment the line for printing the point position on the display.

2. Change the initial value of vector velocity. Try various positive and negative values for the vector's coordinate components x and y.

Loading...