Small Steps II — Making Things

Changing position and drawing again

Change a position and draw again.

What you will learn

Animation displays pictures in succession while changing their state a little at a time. Here, we change the circle's x position.

Try it

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

    double x = 50;

    while (window.is_open())
    {
        x = x + 2;

        if (x > 640)
            x = 0;

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

Each iteration increases x by 2, clears the background, and draws and displays the circle. When it passes the right edge, x returns to 0.

sleep(0.01) waits about 0.01 seconds. Check that the circle moves right and reappears on the left.

Exercise

Place the circle at x=320 in the center of the screen and move it along y. Reverse its direction at the top and bottom edges.

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

    double y = 100;
    double speed = 3;

    while (window.is_open())
    {
        // Update y and bounce.

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

Hint

Create y and speed. Reverse the sign of speed when y > 460 || y < 20.

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

    double y = 100;
    double speed = 3;

    while (window.is_open())
    {
        y = y + speed;

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

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