Timing

Animations in your game mainly happen within the main loop. In it, you can use the game’s time() method to obtain the current GameTime.

The GameTime structure is defined as follows:

// Represents timing information about a running game.
struct GameTime {
    /** The time that has elapsed since the last frame, in fractional seconds */
    double elapsedTime = 0.0;

    /** The time that has elapsed since the game started running, in fractional seconds */
    double totalTime = 0.0;
};

This informs you about how much time has passed since the last call to update was made (delta time). By default, update is called in an interval equivalent to the display’s refresh rate. This means that on a 60 Hz display the delta time would be mathematical expression or equation seconds, assuming that the system is able to keep up with this frame rate.

The following snippet shows how to animate a sprite’s movement based on the total run time of the game.

Time-based animation example
1while (game.tick()) {
2    const auto time = game.time();
3
4    const auto distance = 50.0;
5    const auto speed    = 2.0;
6    const auto offset   = float(cer::sin(spriteAnimationTime * speed) * distance);
7
8    cer::drawSprite(myImage, {100.0f + offset, 50.0f});
9}

Line 2 shows how the current game time is obtained, after which it’s used in line 6 to calculate an offset for the sprite’s position.

The sprite should now move in a wavy pattern along the X-axis, due to the cer::sin function used.

TODO: video