작은 걸음 II — 만들며 배우기
위치를 바꾸며 다시 그리기
위치를 바꾸며 다시 그리기
이번에 배울 것
애니메이션은 상태를 조금씩 바꾸며 그림을 연속해서 보여 주는 것입니다. 이번에는 원의 x 위치를 바꿉니다.
실행해 보기
예제 · example1.cpp
void small_main()
{
Window window;
window.open(640, 480);
double x = 50;
while (window.is_open())
{
x = x + 2;
if (x > 640)
x = 0;
window.clear(Black);
window.fill_circle(x, 240, 20, Yellow);
window.show();
sleep(0.01);
}
}
반복할 때마다 x를 2 늘리고, 배경을 지우고, 원을 그려 보여 줍니다. 오른쪽을 넘으면 x를 0으로 되돌립니다.
sleep(0.01)은 약 0.01초 기다립니다. 원이 오른쪽으로 움직이다 왼쪽에서 다시 나타나는지 보세요.
Exercise — 위아래로 움직이기
원을 화면 중앙 x=320에 두고 y 방향으로 움직이게 하세요. 위와 아래 끝에 닿으면 방향을 바꾸세요.
연습 문제 코드 · exercise1_starter.cpp
void small_main()
{
Window window;
window.open(640, 480);
double y = 100;
double speed = 3;
while (window.is_open())
{
// Update y and bounce.
window.clear(Black);
window.fill_circle(320, y, 20, Green);
window.show();
sleep(0.01);
}
}
Hint
y와 speed를 만들고, y > 460 || y < 20이면 speed의 부호를 바꾸세요.
풀이 보기
void small_main()
{
Window window;
window.open(640, 480);
double y = 100;
double speed = 3;
while (window.is_open())
{
y = y + speed;
if (y > 460 || y < 20)
speed = -speed;
window.clear(Black);
window.fill_circle(320, y, 20, Green);
window.show();
sleep(0.01);
}
}