Small Steps II — Making Things
Bouncing by changing direction
Bounce by changing direction.
What you will learn
The sign of a speed value can represent direction: positive moves right and negative moves left.
Try it
Example · example2.cpp
void small_main()
{
Window window;
window.open(640, 480);
double x = 100;
double speed = 3;
while (window.is_open())
{
x = x + speed;
if (x > 620 || x < 20)
speed = -speed;
window.clear(Black);
window.fill_circle(x, 240, 20, Cyan);
window.show();
sleep(0.01);
}
}
At a boundary, speed = -speed; reverses the sign. Account for the radius of 20 so the center stays between 20 and 620.
This speed is currently distance per iteration. Computers may run loops at different rates, so next we will use elapsed time.
Exercise
Move two balls with different x positions and speeds on one screen. Make both restart from the left after passing the right edge.
Exercise starter · exercise2_starter.cpp
void small_main()
{
Window window;
window.open(640, 480);
double x1 = 50;
double x2 = 200;
double speed1 = 2;
double speed2 = 4;
while (window.is_open())
{
// Update both balls.
window.clear(Black);
window.fill_circle(x1, 180, 15, Yellow);
window.fill_circle(x2, 300, 15, Cyan);
window.show();
sleep(0.01);
}
}
Hint
Create x1, x2, speed1, and speed2 separately.
show solution
void small_main()
{
Window window;
window.open(640, 480);
double x1 = 50;
double x2 = 200;
double speed1 = 2;
double speed2 = 4;
while (window.is_open())
{
x1 = x1 + speed1;
x2 = x2 + speed2;
if (x1 > 655) x1 = -15;
if (x2 > 655) x2 = -15;
window.clear(Black);
window.fill_circle(x1, 180, 15, Yellow);
window.fill_circle(x2, 300, 15, Cyan);
window.show();
sleep(0.01);
}
}