Small Steps II — Making Things
Use the Mouse
Use the Mouse
Explore one topic in small steps. Try the examples one at a time and take a break whenever you need. Choose how many extra exercises you want to try.
A circle that follows the mouse
What you will learn
You can read the mouse position as x and y coordinates inside the window.
Try it
void small_main()
{
Window window;
window.open(640, 480);
while (window.is_open())
{
window.clear(White);
window.fill_circle(window.mouse_x(), window.mouse_y(), 12, Red);
window.show();
}
}
Use the position returned by mouse_x and mouse_y as the circle's center. Clearing the background and drawing at the new position each time makes one circle follow the mouse. Move the mouse inside the window.
Responding 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
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 Yellow circle at the mouse position while the left button is held, and a small Gray circle when it is not held.
void small_main()
{
Window window;
window.open(640, 480);
while (window.is_open())
{
window.clear(Black);
// Draw a different circle while the left button is down.
window.show();
}
}
Hint
Use mouse_down(MouseButton::Left) to separate the two cases.
show solution
void small_main()
{
Window window;
window.open(640, 480);
while (window.is_open())
{
window.clear(Black);
if (window.mouse_down(MouseButton::Left))
window.fill_circle(window.mouse_x(), window.mouse_y(), 25, Yellow);
else
window.fill_circle(window.mouse_x(), window.mouse_y(), 8, Gray);
window.show();
}
}
Try More (Optional)
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.
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();
}
}