ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex Application Developers
| In the first stage of the application, begin with the most fundamental and central task of the application. In an application that involves bouncing circles, the most natural place to begin is to create a single circle that bounces within the boundaries of a rectangle. Here are the steps to complete this stage of the application:
That is all there is to stage one of the application. If you save and test your movie, you should see a single circle that bounces around within the boundaries of a rectangle. The majority of the code in this stage is nothing new or complicated. Some of the mathematics involved in the calculations might be new to you, but the ActionScript syntax is familiar. The only portion of the code that really needs some further explanation is a snippet from the onEnterFrame( ) method. Within this method you want to update the position of the circle according to the direction and velocity for the circle. There are two basic trigonometric formulas that you can employ here to find the new x and y coordinates based on the information you do know (the direction/angle and the velocity). Trigonometry says that the x coordinate can be found by multiplying the cosine of the angle by the velocity, and the y coordinate can be found by multiplying the sine of the angle by the velocity. Now, if the circle was only going to move along a straight line forever, then this would be all that is needed. However, you want the circle to bounce when it hits the sides of the rectangle. Therefore, you need to use a series of if statements. In each case, you must calculate whether the edge of the circle is touching or outside of the rectangle. You can find the edge of the circle by adding or subtracting the radius from the center of the circle (the radius is half of either the width or the height). When the circle needs to bounce, you must do two things. First, set the circle so that it is within the boundaries of the rectangle by at least one pixel. Otherwise, the circle can get trapped along the side of the rectangle. The other thing you should do is assign the circle a new direction. The new direction is determined either by adding twice the difference between p/2 and the current direction (in the case of the circle bouncing off the left or right walls) or by subtracting twice the current direction (in the case of the circle bouncing off the top or bottom walls), as shown in the preceding onEnterFrame( ) handler. |