Small Steps II — Making Things
Changing once per key press
Make one change for each new key press.
What you will learn
key_pressed reports a new press. Distinguish it from key_down, which is true every frame while a key remains held.
Try it
Example · example2.cpp
void small_main()
{
Window window;
window.open(640, 480);
bool is_red = true;
while (window.is_open())
{
if (window.key_pressed(Key::Space))
is_red = !is_red;
window.clear(Black);
if (is_red)
window.fill_circle(320, 240, 60, Red);
else
window.fill_circle(320, 240, 60, Blue);
window.show();
}
}
When Space is newly pressed, is_red = !is_red; toggles true and false. That value chooses is_red or blue. Hold Space, release it, and press it again.
key_released reports the moment a key is released. Down is convenient for movement; Pressed is convenient for a single change.
Exercise
Alternate the circle's radius between 20 and 60 each time Space is pressed. It must not keep changing while Space is held.
Exercise starter · exercise2_starter.cpp
void small_main()
{
Window window;
window.open(640, 480);
bool is_big = false;
while (window.is_open())
{
// Toggle is_big when Space is pressed.
window.clear(Black);
if (is_big)
window.fill_circle(320, 240, 60, Yellow);
else
window.fill_circle(320, 240, 20, Yellow);
window.show();
}
}
Hint
Use key_pressed(Key::Space) and a bool variable to alternate between two states.
show solution
void small_main()
{
Window window;
window.open(640, 480);
bool is_big = false;
while (window.is_open())
{
if (window.key_pressed(Key::Space))
is_big = !is_big;
window.clear(Black);
if (is_big)
window.fill_circle(320, 240, 60, Yellow);
else
window.fill_circle(320, 240, 20, Yellow);
window.show();
}
}