Small Steps II — Making Things

Moving while a key is held

Move while a key is held.

What you will learn

The keyboard state tells you which keys are currently held. key_down is true while a key is held down.

Try it

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

    double x = 320;
    double y = 240;

    while (window.is_open())
    {
        if (window.key_down(Key::Left))
            x = x - 2;
        if (window.key_down(Key::Right))
            x = x + 2;
        if (window.key_down(Key::Up))
            y = y - 2;
        if (window.key_down(Key::Down))
            y = y + 2;

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

Change x and y with the arrow keys and redraw the circle at that position. The screen produced by one loop iteration is a frame.

Key::Left names the left arrow key. Hold the left and right arrow keys and check that the circle keeps moving.

Exercise

Use W, A, S, and D instead of the arrow keys to move the circle up, left, down, and right.

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

    double x = 320;
    double y = 240;

    while (window.is_open())
    {
        // Move with W, A, S, D.

        window.clear(Black);
        window.fill_circle(x, y, 20, Cyan);
        window.show();
    }
}

Hint

Check a letter key with window.key_down('W').

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

    double x = 320;
    double y = 240;

    while (window.is_open())
    {
        if (window.key_down('A')) x = x - 2;
        if (window.key_down('D')) x = x + 2;
        if (window.key_down('W')) y = y - 2;
        if (window.key_down('S')) y = y + 2;

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