A bouncing ball
In the previous section, we implemented linear motion in two dimensions to an object, a circle. This circle is defined inside a square. If the circle goes off screen from the top, it will appear at the bottom and vice versa. If it goes off screen from the left side, it will appear on the right side, and vice versa.
We can change this setup in order to create the illusion of a bouncing ball inside a box. For doing this, we need to replace the last two lines in the slider Run:
If( x(O) > 10, SetValue( xlocation, -10 ), If( x(O) < -10, SetValue( xlocation, 10) ) )
If( y(O) > 10, SetValue( ylocation, -10 ), If( y(O) < -10, SetValue( ylocation, 10) ) )
with the following:
If( x(O) > 10 || x(O) < -10, SetValue(xvel, xvel * (-1)) )
If( y(O) > 10 || y(O) < -10, SetValue(yvel, yvel * (-1)) )
The following applet shows the result:Exercise
Notice that the ball bounces considering the centre of the circle. Try implementing a bouncing ball considering the boundary of the circle instead.