Small Steps II — Making Things

Moving according to actual time

Move according to actual time.

What you will learn

Distance = speed × time. Choosing a speed per second and moving by the elapsed time keeps movement consistent even when loop rates differ.

Try it

Example · example2.cpp
void small_main()
{
    Window window;
    window.open(640, 480);

    double x = 50;
    double speed = 200;

    StopWatch watch;

    while (window.is_open())
    {
        double dt = watch.elapsed();
        watch.reset();

        x = x + speed * dt;

        if (x > 620 || x < 20)
            speed = -speed;

        window.clear(Black);
        window.fill_circle(x, 240, 20, Yellow);
        window.show();
    }
}

dt stores the time since the previous iteration. Read it with elapsed, then reset the watch, and add speed * dt to the position.

At 200 pixels per second, the object moves 2 pixels in 0.01 seconds and 4 in 0.02 seconds. dt is not new syntax. Change speed to 100 and compare.

Exercise

Update the vertically moving ball from lesson 44 to use dt and a speed of 150 pixels per second.

Exercise starter · exercise2_starter.cpp
void small_main()
{
    Window window;
    window.open(640, 480);

    double y = 100;
    double speed = 150;
    StopWatch watch;

    while (window.is_open())
    {
        // Measure dt and move using seconds.

        window.clear(Black);
        window.fill_circle(320, y, 20, Green);
        window.show();
    }
}

Hint

Each loop, use double dt = watch.elapsed(); watch.reset();, then move with y = y + speed * dt;.

show solution
void small_main()
{
    Window window;
    window.open(640, 480);

    double y = 100;
    double speed = 150;
    StopWatch watch;

    while (window.is_open())
    {
        double dt = watch.elapsed();
        watch.reset();

        y = y + speed * dt;

        if (y > 460 || y < 20)
            speed = -speed;

        window.clear(Black);
        window.fill_circle(320, y, 20, Green);
        window.show();
    }
}
← Previous lessonNext lesson →