# Lesson 3.2

## If we move to the right by adding 1 to x with every call to draw(), ## we can move to the left by subtracting 1 from x with every call to draw(), ## Whenever we reach the boundary of the canvas, that is, whenever the condition x > 400 is met (assuming a canvas width of 400), we would like to switch. Overall we might write, ## But it does not work! The ball just gets stuck in the wall! ## We need to find a way to make the change from adding 1 to subtracting 1 permanent. We would like to replace line of code ## with ## We can do so by replacing the operations + 1 and – 1 with a variable. Since the 1 represent how fast we are moving, we can call the variable speed. Our line of code (assuming that we previously set speed = 1) that makes the circle move would now be ## We need to change the speed from 1 to -1. We do so by multiplying speed by -1. ## Example 3.2.1

One small addition. We are likely not satisfied with the fact that the circle is half way in the wall before it even looks top bounce off. We can fix this by having the condition for changing direction not be when circle.x = 400 but when circle.x = 390. It would then only move 1 pixel into the wall (not visually noticeable) before changing direction.

We could still look for a more general solution to this problem. It would be fine as a long as the speed is not much greater than the radius of the circle, however it would be a more general solution to bounce when circlcle.x > width – circle.radius, where width is the width of the canvas and circle.radius the radius of the circle, rather than when circle.x = 390 which only applies to these particular conditions of width and circle radius.

## Exercise 3.2b: Have two balls, a red and a blue, bouncing off all 4 walls, but have the red ball trapped in a smaller box at the center. Both are moving twice as fast along the vertical as compared to the horizontal. The blue moves behind the center box. 