Development environment



Chapter 11: Ballistics simulation

This chapter builds on the previous one to describe ballistics simulation, namely, the simulation of the firing of a projectile into the air. When studying this chapter, you will

• learn the basic mathematics and physics of projectile motion, including simulation of the effects of gravity

• practice building an application involving collision checking

• understand the benefits of dividing a project into steps

• gain experience using the Flash features for Clipevents, the hitTest method, adding audio effects, and providing drop and drag operations

Motivating Example

The cannonball application featured in this chapter can serve as a basis for a shooting type of game. The initial screen is

[pic]

Figure 1. Opening screen of cannonball.

The player clicks on the FIRE button. The cannonball travels in an arc and either hits the ground or the target. The player can change the angle of the cannon by entering a new amount in the field next to the static text field Degrees, initially set at 45, or can change the speed out of the mouth of the cannon by changing the text field next to the static text field Speed, initially set to 10. The player also can drag the target using the mouse buttons.

If the ball hits the target, it turns red and tilts, with a sound played. Figure 2 shows the screen after a successful firing of the cannon.

[pic]

Figure 2. Screen after the cannonball hits the target and it tilts.

The critical features required by this application include

• the features described for the bouncing ball application: the ability to re-position objects on the screen and to produce animation by doing the re-positioning at intervals of time

• calculating vertical and horizontal components of velocity

• calculating the effects of [simulated] gravity to produce the characteristic arc of projectile motion

• determining collisions

• calculating the orientation of a tilting object

• changing the color of a Flash movie clip

• producing a sound

TIP: This application requires some basic mathematics. Do not be frightened. The equations are all supplied and you will not need to consult any tables or do any calculations. What you need to do is understand the use of built-in Math methods. Seeing the mathematical functions in use should help your understanding.

Introduction to concepts

When someone throws a ball or shoots an arrow or fires a missile, the projectile travels in an arc in the shape of a parabola. This is because the force of gravity acts on the object. In the previous chapter, it was noted that the requirements of most computer systems made it necessary to separate the horizontal and vertical components of velocity. Ballistics simulation provides another reason for this separation. Gravity acts to change the vertical component, not the horizontal component. The horizontal component is changed by forces such as the drag from the air, but we assume a more idealized situation. The horizontal velocity remains constant and the vertical velocity changes.

EXAMPLE: The simulation is to move (animate) the cannonball through the air using calculations based on the initial velocity out of the cannon, the resolution of that vector into horizontal and vertical components, and the effects of gravity to change the vertical vector.

In simulations involving virtual worlds, the program often must check if the position of one object overlays the position of another. A generic term for these checks is collision detection. The checks are to determine if the virtual objects collide.

EXAMPLE: Checks are made to see if the cannonball hits the ground or hits a target. These checks are set up to be done throughout the flight using different programming techniques.

The simulation is enhanced by allowing the player to change the angle of the cannon and the velocity out of the cannon. The player also can move the target by dragging and then dropping it using the mouse. Lastly, the simulation produces a sound and makes the target slowly rotate when the hit is detected. These all involve various coding techniques, some specific to Flash, and others applicable to other programming languages.

A lesson for all programming is to divide implementation into steps. This will be demonstrated by dividing the implementation of the cannonball application into multiple steps. This is an important principle to keep in mind for all projects.

Description: simulation of projectile motion

In the bouncing ball simulation, the ball is re-positioned horizontally and vertically over and over again to produce the look of animation. For the cannonball simulation, it is necessary to determine the horizontal and vertical components of the velocity. The initial information is the speed of the cannonball out of the cannon and the angle of the cannon. Figure 3 shows how the vector v representing the cannonball departing the cannon oriented at angle a can be decomposed (resolved) into horizontal and vertical vectors, vx and vy. [pic]

Figure 3. Initial speed as sum of component parts.

The magnitude of the two vectors turns out to be easy to calculate using the built-in trigonometric functions. Look at the triangle shown in Figure 3. It is a right triangle, meaning that two of the sides are perpendicular. The side opposite the right angle is called the hypotenuse. The angle at the left is of size a. In any triangle of this shape, meaning any right triangle with one of the other angles of size a, the ratio of the side next to angle a, vx, to the hypotenuse, v, is the same known value called the cosine of the angle a. Similarly, the ratio of the side opposite, vy, to the hypotenuse, v, is the same known value, called the sine of the angle a. These ratios are definitions of the trigonometric functions sine and cosine.

Using pseudo-code and the common abbreviations of the functions:

vx = v * cos(a)

vy = v * sin(a)

Most programming languages have built-in functions or methods for producing the trigonometric functions and this is the case with ActionScript:

vx = v * Math.cos(a);

vy = v * Math.sin(a);

Math.cos and Math.sin are class methods. The parameter a is the angle. Stating this in practical terms, once the value v, the velocity of the cannonball out of the cannon, and the angle a, the rotation of the cannon, are known, you can write the code to calculate the horizontal and vertical velocities for moving the cannonball.

TECHNICAL NOTE: What are the units for the angle? This question may not have occurred to you because you assume that degrees, 360 indicating a full circle, are the only way of measuring angles. We all are familiar with degrees--90 degrees to a right angle; making a u-turn is "doing a 180"--but this measurement is totally arbitrary and it is not the only possibility. Many computer programming languages use radians in place of degrees. Imagine taking the radius of a circle and using it as the ruler to measure the arcs around the circle. There are 2 * pi radians to go all the way around. One radian is a little less than 60 degrees. This unit may seem strange to us, but calculations are easier. Consequently, radian is the standard unit for many programming languages. You need to determine what units the built-in trigonometric functions expect and adjust accordingly.

The cannonball application expects the player to input the angle in the familiar degrees. The built-in functions expect angles to be expressed in radians. The program, therefore, must make the conversion. Fortunately, ActionScript provides a Math class variable Math.PI. The code for the conversion is

angle_radians = angle_degrees * Math.PI/180

Now that is clear how to determine the initial values to use to animate the cannonball, it is time to move on to describe how to include the effects of gravity. The vertical velocity must change. Exploring this requires a return to the equations of motion. Velocity changes position: it causes displacement. The displacement is calculated using the formula

new_position = old_position + velocity * time

Gravity is a force that brings about acceleration. Acceleration changes velocity. The technical term acceleration means any change in velocity, not just getting faster by pushing on the car gas pedal. Acceleration can mean going faster or slower and it also can refer to changes in direction. The relevant formula is

new_velocity = old_velocity + acceleration * time

Assuming constant acceleration, the velocity at the end of the time interval chosen for the simulation is the velocity at the start of the interval plus the value of the acceleration. Note that the sign (positive or negative) of the acceleration does not matter for these equations to be valid. What is the velocity to be used for re-positioning the object? The answer is to take the average of the starting and ending values.

average_velocity = (old_velocity + new_velocity)/2

Combining the last two equations,

average_velocity = (old velocity + old_velocity+acceleration*time)/2

Now putting this value into the displacement equation,

new_position =

old_position + ((old_velocity+old_velocity+acceleration*time)/2)*time

Simplifying this

new_position = old_position + old_velocity*time + .5 *acceleration*time2

The simplification is done to show that the value assigned for the new position is a quadratic expression in terms of the time variable. This is the reason that the path is a parabolic arc. The horizontal component of the velocity remains constant so the object keeps moving horizontally as it started. The horizontal movement is proportional to the time elapsed. The vertical component undergoes the changes corresponding to the quadratic expression. For the ballistics simulation, assuming the cannon is pointing up and to the right, the vertical velocity begins moving the projectile upward, changes to moving upward slower and slower, then changes to moving downwards, then moving downwards faster and faster. Figure 4 is an attempt to convey this.

[pic]

Figure 4. Arc (may not be perfect parabola!)

When you get to the coding, you will learn about the signs of the relevant variables and how this produces the desired effect, but this mathematics and physics lesson is over. If you work on action games or simulation of many phenomena of nature, you will need to explore more equations such as these involving forces and vectors.

Description: collision detection

The ballistics simulation featured in this chapter requires two calculations involving collisions: the ball hitting the ground and the ball hitting the target. The object nature of Flash and ActionScript provide features that makes the programming more-or-less intuitive but in this and other programming environments, it is important to understand that you, the programmer, need to check explicitly for the conditions that indicate a collision. There are no cannonballs, targets and ground inside the computer.

Graphical objects are characterized by their positions on the screen or in the virtual world and numbers or formulas defining their shapes. The position generally is the location of the registration point or nominal origin of the object so it is critical to know what the registration point is. In Flash, the registration point would be indicated by a + sign on the Stage. You draw the graphics keeping this registration point in mind. However, if it turns out that you need to re-position the graphics in terms of the registration point, you can select everything using the arrow selection tool and move the material. Alternatively, you can change the coordinates given in the Properties panel directly.

Figure 5 shows 4 rectangles with circles representing the registration points. (A filled-in circle is used here to indicate the registration point.) The first rectangle has the registration point in the middle. The next two on the top row have the registration point in or near corners. The rectangle on the bottom row has the registration point away from the rectangle itself. When these items are positioned, the value of the position coordinates is the location for the registration points.

[pic]

Figure 5. Examples of registration points.

Figure 6 shows stars positioned 'near' the rectangles, that is, near the rectangle registration points. Notice the very different effects.

[pic]

Figure 6. Rectangles positioned.

TIP: The registration point or origin may or may not be under your control. For example, images in HTML are positioned in terms of the upper left corner. In Flash, you can define the registration point to be anywhere you want, including making it away from the actual graphical material.

If you know the registration point and the shape of an object, you can write code to determine if a point is within the boundaries of an object. The Flash system has a method that performs such tests, which will be explained next. However, just in case your language does not have it, and to increase your understanding, consider the following situation involving a rectangle. If a rectangle's origin is the upper left corner and

origin at rx, ry

width rwidth

height rheight

and the question is whether or not the point mx, my is within the rectangle, the check is the compound if test

if ((mx>=rx) && (my >= ry) && (mx ................
................

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

Google Online Preview   Download