Small Steps II — Making Things
A circle that follows the mouse
Make a circle follow the mouse.
What you will learn
You can read the mouse position as x and y coordinates inside the window.
Try it
Example · example1.cpp
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.
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.
Exercise starter · exercise1_starter.cpp
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();
}
}