Small Steps II — Making Things
Responding to mouse buttons
Respond to mouse buttons.
What you will learn
The mouse's position and button state are separate. Reading both lets you act at the clicked location.
Try it
Example · example2.cpp
void small_main()
{
Window window;
window.open(640, 480);
while (window.is_open())
{
window.clear(White);
if (window.mouse_down(MouseButton::Left))
window.fill_circle(window.mouse_x(), window.mouse_y(), 30, Blue);
else
window.draw_circle(window.mouse_x(), window.mouse_y(), 30, Black);
window.show();
}
}
mouse_down(MouseButton::Left) asks whether the left button is held. The program draws a blue circle while held and a black outline when released.
mouse_pressed reports a new press; mouse_released reports a release. Use Pressed to remember a position once.
Exercise
Display a Red circle at the mouse position when the left button is held, and a Blue circle when the right button is held.
Exercise starter · exercise2_starter.cpp
void small_main()
{
Window window;
window.open(640, 480);
while (window.is_open())
{
window.clear(White);
// Left = red, Right = blue.
window.show();
}
}
Hint
Check mouse_down for Left and Right separately.
show solution
void small_main()
{
Window window;
window.open(640, 480);
while (window.is_open())
{
window.clear(White);
if (window.mouse_down(MouseButton::Left))
window.fill_circle(window.mouse_x(), window.mouse_y(), 30, Red);
if (window.mouse_down(MouseButton::Right))
window.fill_circle(window.mouse_x(), window.mouse_y(), 30, Blue);
window.show();
}
}