Development environment



Chapter 10: Computed animation

This chapter will introduce the topics of simulation and animation, common applications of computer programming. After studying this chapter, you will

• understand what is meant by discrete simulation

• appreciate differences between discrete simulation and continuous real-life

• have practiced building a virtual world for a 2-dimensional simulation of a bouncing ball enclosed in a box

• know how to use calculations to re-position objects on the screen to produce animation

• have learned how to use Boolean and other types of variables to toggle (switch back and forth) between different actions

• have gained experience using Flash movie clips, buttons, text fields and the movie clip method hitTest

Motivating Example

The application featured in this chapter is not really a game, though you can build on it to create one. The opening screenshot is shown in Figure 1.

[pic]

Figure 1. Opening screen for bouncing ball.

The ball is in motion, bouncing against the walls. The player can click the button to stop the ball. The text on the button will change to indicate what the button will do.

[pic]

Figure 2. Screen shot of bouncing ball stopped.

The button toggles the game between two states: the ball moving and the ball at rest.

The player can change the text field showing 100 to make the ball move at a different velocity.

The critical features required by this application include:

• a way to position graphical elements at different places on the screen

• a facility to do something, namely re-position graphical elements, at short intervals of time

• determining if a [virtual] collision has taken place

• calculating two-dimensional movement

Introduction to concepts

Real life is continuous but most simulations portray what is being simulated at discrete intervals. That is, the simulation is a representation of what is being simulated at one point in time and then at another point in time a little later. This can be adequate or not, depending on the situation.

If you have examined a movie reel, you know that a movie consists of a sequence of still pictures that are projected at a fast enough pace that the human eye does not see the individual pictures but, instead, perceives movement. Animation is produced in the same way.

In cel or frame animation, a sequence of static pictures are created as part of the production process. At runtime, the pictures are displayed to the viewer. It may be that the individual pictures are produced using computer programming so this can be called computer animation. However, the animation featured in this chapter and the next is different. The program changes what appears on the screen as the program runs. The scene is computed dynamically by positioning and re-positioning the objects using calculations of what the positions would be based on conditions.

EXAMPLE: the bouncing ball application will show a ball moving in a 2-dimension box, bouncing against the walls. It works by re-positioning the ball by adjusting its horizontal and vertical properties. The application includes calculations to check if the ball has hit any of the 4 walls, that is, if the position of the ball and the position of the walls overlap.

Description: three-dimensional modeling

The many games that feature 3-D require complex programming, outlined here briefly. The entities (characters, buildings, etc.) are represented by 3-D models: generally collections of polyhedra, flat-sided objects approximating more complex shapes. Surfaces may be represented by mathematical equations, sometimes involving pseudo-random calculations in order to simulate nature. Often 2-D patterns and images are wrapped around 3-D surfaces. Action in the game means movement of the models. A simple act of a character walking corresponds to a complex re-positioning of the geometric shapes making up the character along with calculations such as collision-detection. The program must generate the display on the flat screen over and over again to trick the human eye into seeing live action. The tasks include for producing the display include

• determining the projection plane based on a position for the eye or camera and a focal point. First-person-shooter games use the eye position of the character representing the player.

• clipping the projection based on the dimensions of the screen

• solving the hidden line / hidden surface problem: material is covered up (occluded) by other material. See Figure 3.

• calculating the effects of lighting based on position and types of light sources along with models specifying the reflectivity of all the surfaces

[pic]

Figure 3. Wire-frame versus hidden line.

Software exists to support these tasks, but it is still an area of active research for games, movies, and scientific visualization.

Description: 2-D movement

The application featured in this chapter is a ball, bouncing within a box made up of 4 walls. The virtual world is 2-dimensional. The movement of the ball is simulated by re-positioning the computer object representing the ball periodically, that is, at set time intervals. The positioning is done in terms of horizontal and vertical coordinates. The position is based on the equation of motion from the study of physics:

new_ position = old_ position + velocity * time

The time in this equation refers to the time interval or time elapsed. The term velocity is used to convey speed and direction. The equation is a vector equation, meaning that new_position, old_position and velocity are each vectors.

REAL-LIFE NOTE: Before getting into the vector calculations, consider the following examples from everyday life: If at 10am, you are 20 miles from home, traveling at 50 miles/hour, then at 11am, you will be 70 miles from home. At 11:30, you will have traveled 25 miles further to be 95 miles from home. See the exercises for more problems. Note that the phrase 'from home' sets this up as a one-dimensional problem.

Vectors are added by putting them together head to tail as illustrated in Figure 4.

[pic]

Figure 4. Vector addition.

When programming, addition of vectors generally is done using the component parts. For example, in the 2-dimensional situation, each new position is establishing using two equations

positionx = oldx + velocityx * time

positiony = oldy + velocityy * time

The velocityx is the x-component of the velocity. Figure 5 shows the velocity vector as the sum of the x and y components. Resolution is the operation of calculating the components, done using the trigonometric functions.

[pic]

Figure 5. Resolution of vector.

Some applications start off with the velocity and require calculation of the x and y components and some start off with the components directly. The cannonball application featured in the next chapter assumes a velocity given as the velocity out of the cannon. The program computes the components. In the bouncing ball application, the components are assumed to be the same and equal to what is in a text field that can be changed by the player.

TECHNICAL NOTE: Coordinates for computer displays typically have the horizontal coordinate increasing from left to right and the vertical coordinate increasing moving down the screen. As has been indicated previously, this can be disconcerting since moving up corresponds to moving in a negative direction.

The movement of the ball is done by applying the equations repeatedly. The use of timed events has been discussed in previous chapters. What is required here is an event that keeps recurring at time intervals of a specified duration. Experimentation with the length of the duration will make the ball appear to move continuously and smoothly.

Description: collisions

The simulation of the ball in a box may seem straight-forward: keep moving the ball until it hits one of the walls and, if and when it does, reverse direction. However, here is where the fact that this is a discrete simulation of a continuous process becomes significant. The position of the ball is checked at discrete intervals. Consider the situation illustrated in Figure 6. The ball is in front of the wall at the time equals T1 and then beyond the wall at time equals T2.

[pic]

Figure 6. Ball in front and beyond wall.

You can lesson these effects by making the time duration smaller and smaller and making the walls thicker also helps, but the problem never goes away entirely. Think of it as checking up on the ball's whereabouts by making an instantaneous check every so often. You miss what happens 'in-between' checks.

When the ball hits a wall, the direction of movement will change in a manner dependent on which wall was hit. If the ball is heading downward and to the right, hitting the wall on the right will change the travel to moving downward but now to the left.

[pic]

Figure 7. Direction of travel after hitting wall.

This turns out to be easy to program. Two variables, one for the horizontal motion (lrdir) and one for the vertical motion (uddir), can indicate direction of travel. The statements

ball._x += (lrdir * moveAmount);

ball._y += (uddir * moveAmount);

carry out the equation of motion indicated previously. The x and the y coordinate of the object are each increments (using the += operator) by moveAmount, the amount of displacement calculated using the velocity. The lrdir and uddir variables are each 1 or -1.

When hitting the left or right wall, the horizontal variable, lrdir, changes sign. When hitting the top or bottom wall, the vertical variable, uddir, changes sign.

REAL-LIFE NOTE: In nature, balls hitting surfaces lose energy and, therefore, velocity. The coefficient of restitution, dependent on the materials of the ball and the wall, indicates how much the velocity changes. Rubber balls bounce higher than bowling balls! Tennis players may specialize in different surfaces.

EXAMPLE: The bouncing ball application featured here assumes an ideal situation in which the ball rebounds completely, but you can look at the exercises for a challenge.

Reading Checks

1. Compare discrete versus continuous in terms of simulation.

2. Consider the workings of a digital clock and a (old-fashioned) face clock with hands and compare this to discrete versus continuous simulation.

3. Describe how the movement of the ball is achieved by changing two properties corresponding to vertical and horizontal placement.

4. Distance traveled equals velocity times time. Use this formula to determine distance traveled by an object going 12 meters/second after one-half, 1, 2, 3, and 4 and 1/2 seconds.

Application

This section reviews briefly the use of coordinates and timed events in previous chapters and then goes on to describe the bouncing ball simulation.

Review of previous examples

The Find Daniel game demonstrated the use of coordinates as well as a timed event. The coordinates define what would be a correct guess by the player. The timed event was used in the timed version of the game. The JavaScript function used was setTimeout. This sets up a one-time event. The pause in the memory game makes use of setTimeout as well. For Flash, the process events, timersetup and timermonitor, perform a similar function. JavaScript also provides a setInterval function that sets up events to occur repeatedly until the timed event is turned off. This would be more appropriate for animation. For the implementation in Flash described here, timed events are produced using frames.

Plan of attack for bouncing ball

The timing of the animation will be done using the frames of Flash. The timeline (Figure 8) will hold 3 frames.

[pic]

Figure 8. Bouncing Ball Timeline.

The first frame is for initialization and one function definition. The second frame holds free-standing (not in a function) code for checking for hitting the walls. The third frame has free-standing code to go to the second frame or to stop depending on whether or not the ball is in motion.

The application has 3 symbols in the Library:

[pic]

Figure 9. Library for bouncing ball.

The symbols are a movie clip representing the ball; a button symbol for the button stopping or resuming play; and a movie clip representing a wall. You will create these and then move one instance of the ball, one instance of the button, and 4 instances of the wall to the Stage. Each movie clip instance must have an instance name.

The text field in the button that holds either Stop Ball or Resume must be a Dynamic text field, with a Var of caption. This is so the code can change the text field.

[pic]

Figure 10. The stopgo button, with the Dynamic text field var name caption.

You must set up an Input Text Field to hold the speed of the ball. This is done using the A tool in the Tools to create a text field and then use the pulldown menu in the Property panel to make it an Input text field. This text field will be treated differently: set the Instance field name to speed.

[pic]

Figure 11. Properties panel for giving an Instance name to the Input Text field.

Use of concepts in implementation

The program simulates the actions of a ball by moving the ball movie clip according to the equations of motion.

As indicated in the previous section, you will need to create a wall movie and then move 4 instances of the wall to the Stage, naming each one. You will transform two of these instances to form the walls of the box as shown in Figure 12.

[pic]

Figure 12. Menus for transforming a wall instance.

The passage of time is indicated by the playing of frames. The amount of time is calculated using two variables, now and then and a built-in function getTimer. The function returns the number of milliseconds that have passed since the program started.

The ActionScript in the first frame starts with declaring variables:

var continueflag = true;

var now = getTimer();

var then = 0;

var elapsed;

var moveAmount;

The first frame has free-standing code that initializes certain variables. This code is only executed once:

if (speedt ==undefined) {var speedt = 100;}

if (lrdir == undefined) {var lrdir = 1;}

if (uddir == undefined) {var uddir = 1;}

The very first time this code is executed, the speedt, lrdir and uddir will be undefined. In the subsequent times that frame 1 is played, these if tests will fail.

Lastly, the frame contains one function definition. This function, toggle, is invoked by the on(release) event of the stopgo button.

|function toggle() { |function header |

| if (caption=="Stop ball") { |Use the dynamic text field on the button to check which |

| |of the two states: if it says "Stop ball" |

| continueflag = false; |… set flag to false |

| caption = "Resume"; |change caption to "Resume" |

| } |End true condition |

| else { |Else |

| speedt = speed.text; |Set value for speed |

| caption = "Stop ball"; |change caption to "Stop Ball" |

| continueflag = true; |… set flag to true |

| now = getTimer(); |Get latest time |

| } |End else |

| goToAndPlay(2); | |

|} |End function |

The ActionScript in frame 2 is all free-standing code. The ball is moved and then a check made for colliding with each of the walls. The move is done, as indicated earlier, using the += operator and the variables lrdir and uddir holding 1 or -1.

|speed.text = speedt; |Set the text field. |

|then = now; |Assigning the value of now to then for the later|

| |calculation of the elapsed time |

|now = getTimer(); |Acquire current time |

|elapsed = now - then; |Calculate elapsed |

|numSec = elapsed/1000; |Turn it into seconds |

|moveAmount = speed.text * numSec; |Change in position equals speed times time |

|If (continueflag) { |If the ball is to be moving… |

|ball._x += (lrdir * moveAmount); |Adjust in x |

|ball._y += (uddir * moveAmount); |Adjust in y |

|if (ball.hitTest(rightwall)) { |Check if colliding with right wall |

| lrdir = -lrdir; |change left right variable |

|} |End clause |

|if (ball.hitTest(leftwall)) { |Check if colliding with left wall |

| lrdir = -lrdir; |change left right variable |

|} |End clause |

|if (ball.hitTest(upperwall)) { |Check if colliding with upper wall |

| uddir = -uddir; |change up down variable |

|} |End clause |

|if (ball.hitTest(lowerwall)) { |Check if colliding with lower wall |

| uddir =-uddir; |change up down variable |

|} |End clause |

|} |End if in motion clause |

A natural inclination is to try to make the code more efficient by trying to not check if the ball has collided with the right wall if it has collided with the left and similarly for up and down. The approach here is to make the statements simple. It often is the case that a brute force approach is the most efficient.

The ActionScript in frame 3 tests if the ball is in motion and either goes back to frame 2 or stops. Note that the stopgo button is still operational even if the movie is stopped at frame 3.

if (continueflag) {

gotoAndPlay(2);

}

else {stop();}

The event handling for button is specified by selecting the button and entering the following lines of code. It sets up the toggle function defined in frame 1 as the event handler for clicking and releasing the button.

on (release) {

toggle();

}

Reading Check

1. Describe how the timed event is achieved using Flash frames. Compare this to the use of setInterval in JavaScript.

2. What does the toggle function do? How is it invoked?

3. Why does 'hitting a wall' change only one of the two direction variables?

4. What is the meaning of undefined in free-standing code in the first frame? How is it used?

What can go wrong

A common syntactic mistake made in this type of application is to fail to give Var names to the text fields: the caption in the button (see Figure 10) and the speed text field in the main scene (see Figure 11). You also must be sure to give distinct instance names for each of the wall instances as shown for the rightwall in Figure 13.

[pic]

Figure 13. Giving a wall instance a name.

You do need to make sure that hitting the left or right wall means a change in lrdir and hitting the upper or lower wall means a change in uddir. Notice that it is not necessary to know the sign of these variables. All that is necessary is to change the sign.

Chapter Summary and Reflection

This chapter focuses on computed animation, adding the features necessary to display a 2-dimensional ball moving in an enclosed box. A graphical object, the ball, is moved incrementally across the screen, fooling our eyes into perceiving motion. The implementation is done using the playing of frames of Flash. The test for colliding with the walls is performed using the movie clip method hitTest. The player can start or stop the action and can change the speed.

The calculation involving the call to getTimer and the variables now and then could be simplified to move the ball a fixed amount each time the frame action is run. The playing of the frames is performed at a fixed rate so it can be assumed that the amount of time is always the same. (You can change the fixed rate. Try it.) The rationale for this fancier code is to make it easy to relate to actual values if you wanted to simulate a real speed.

The timed event in this application uses the playing of frames in the main movie. In the application in the last chapter, the onClipEvent(enterframe) coding was a way to use the playing of frames in a movie clip instance, namely the timermonitor instance in the timersetup instance. This is necessary for effects such as pausing.

If you were a programmer

This is a basic simulation / animation application. Simulations are done to understand and test systems. Industrial organizations simulate systems before deploying them. Animations can be considered simulations rendered in graphical form.

What's next

The next chapter, Chapter 11, uses the same programming techniques in Flash and ActionScript to simulate the firing of a cannonball out of a cannon that either hits a target or falls to the ground. Chapter 12 describes discrete simulation of a different kind, finite-state simulation. The thing being simulated is the behavior of a dog. The tools used for that implementation are HTML and JavaScript.

Exercises

1. Compare the relationship of a digital clock and a 'face' clock with discrete versus continuous simulation.

2. You are driving a car at 45 miles/hour. How far do you go in 1 hour? 2 hours? 20 minutes? 90 minutes?

3. You read a book at the rate of 2 pages/minute. How many pages can you read in 30 minutes.

4. Write the code to move a movie clip named house off stage on the left.

5. Write the code to move a movie clip named house off stage, above the Stage.

6. Write the code to move a movie clip named roof positioned 10 pixels above a movie clip named house and at the same horizontal location. (Hint: two statements)

7. True or False: when the virtual ball hits the virtual right wall, both the horizontal and vertical directions need to change.

8. True or False: an input text field is accessed using the name given in a static text field acting as a label next to it. (Trick question.)

Projects

9. Change the bouncing ball to allow for specifying separately the horizontal and vertical velocities (speeds) using 2 distinct text fields.

10. Change the bouncing ball to make the ball slow down each time it hits a wall by specifying that the velocity for the relevant component changes by a certain factor, say .95, thus reducing the speed.

11. The hitTest method, as indicated, compares the bounding rectangles. Make the walls more irregular in shape. You even may choose to make the walls 4 distinct movie clips instead of 4 instances of the same movie clip. Change the call to be a method of each of the wall instances and use the form of hitTest that compares an x,y position against the material of the movie clip: leftwall.hitTest(ball._x, ball._y, true);

This works best if the origin of the ball is at the center.

Note that you still need to make sure that the ball does not travel past the wall, that is, through it, in-between iterations.

12. Enhance the application to allow the player to specify the initial position for the ball and the initial velocity (meaning both the horizontal and vertical components).

13. Building on the prior exercise, construct a pool-like single shot game. One approach is to construct walls with gaps and into the gaps position movie clip instances representing pockets. When the ball hits a wall (for example, when leftwall.hitTest(ball._x, ball._y, true) returns true), the ball bounces as in the original game. You need to use this version of hitTest, which compares the x,y position to material not bounding rectangle to bounding rectangle. When the ball hits a pocket instance, the player scores a point.

For teachers only: Tips for Teachers

This application serves as preparation for the cannonball application featured in the next chapter, but it deserves time and attention on its own. Simulation and animation are important topics in a variety of fields. Students do enjoy enhancing the graphics and doing silly things such as replacing the ball graphic with someone's face.

The discrete versus continuous distinction is important. You can bring up the issue of which are more accurate: analog instruments with continuously moving dials or digital instruments. If you did not have this text, you could allow the students to discover on their own that the ball can get past the walls, and it still may happen to students who do not read the text carefully.

It is possible to implement a bouncing ball type application in HTML and JavaScript, but it requires a way to handle the difference between browsers. For this reason, the Flash implementation seemed the better choice.

-----------------------

velocityx

velocity

velocityy

+

=

at T1

at T2

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download