1. Trang chủ
  2. » Công Nghệ Thông Tin

Macromedia Flash MX Game Design Demystified phần 2 pdf

38 388 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 38
Dung lượng 733,49 KB

Nội dung

convince yourself of how this works, try this example in Flash: input=.707; trace(Math.asin(input)*180/Math.PI); Line 1 sets a variable called input with a value of .707 . Line 2 uses the inverse sine method of the Math object (which returns an angle in radians) and then converts it to degrees. The result is traced in the window and should be very close to 45°. (It is not exactly 45° because the true sine of 45° has many more decimal places than .707.) Projection The word projection in the context of trigonometry means to project a quantity (such as distance or velocity) onto the x-axis and y-axis. Using what you'll learn in this section will help you when building games. For an example of what projection can you accomplish, open the file shooter.fla in the Chapter03 folder on the CD-ROM. In this file, a ship rotates to point toward your mouse. When you click anywhere on the movie's stage, a projectile fires from the nose of the ship. The velocity of the points toward your mouse (or at least to the place where your mouse was when you clicked it). In order for this movement to be pro g rammed in Flash, the velocity must projected along the x-axis and y-axis. Imagine a diagonal line of length len drawn in Flash at angle ang. A piece of this line extends along the x-axis and another piece of it along the y-axis. If the angle were 0°, then the line would extend only along the x- If the angle were 90° then the line would extend only along the y-axis. With any other angle, the line both in the x direction and the y direction. (Put another way, no two coordinates on the line have the same x y value: A horizontal line always has the same y value for all of its coordinates. A vertical line always has the same x value for all of its coordinates. A diagonal line never repeats an x or y coordinate.) If you were to a right triangle from this diagonal line, then the two other sides of that triangle would be the pieces that along the x-axis and y-axis. Finding the length of either (or both) of those pieces by using the values ang and len is called projection. values are found by using the trigonometric functions that we've already discussed above. The programmatic movement seen in this example file is not covered until Chapter "Basic Physics." As seen in the previous section: cos(angle)= x/c In the example here, angle is replaced with ang and c with len. So: cos(ang)= x/len To find the projection of len along the x-axis, we solve for x: x =len*cos(ang) Or with ActionScript: x=len*Math.cos(ang); To find the y projection we use sin(ang)= y/len And solve for y: y=len*sin(ang) Which converts to this in ActionScript: y=len*Math.sin(ang); Think of projection like a shadow cast from an object onto the floor or a wall. For the example given in this section, first we would imagine a light source coming from below to cast a shadow on the x-axis. The length the shadow cast from the line on the x-axis is the same as the projection we would calculate using trigonometry. Next we would imagine a light source coming from far off to the right shining left. The cast on the y-axis is equal to that which we would calculate using trigonometry. I l @ve RuBoard I l @ve RuBoard V ectors A vector is a mathematical object that has both magnitude (a numeric value) and direction. Velocity is a because it has both magnitude and direction. For example, a velocity of 33 kilometers per hour (kph) has a magnitude of 33 and a direction of southeast. Speed is not a vector, and direction is not a vector, but speed and direction together, modifying the same object, form a vector. Here are some other examples of vectors. z Displacement can be a vector when describing the location of one point with respect to another point (whether those points represent two objects, or one object in motion). For example, "New York is miles north of Virginia" or "The ball rolled 3 feet to the left." z Force can be a vector, since the gravitational force that pulls you toward the earth has both a magnitude and a direction. z Rotation, when modified with a direction, is a vector. Think of a clock hand, rotated 90° clockwise. Graphically, a vector is usually represented as an arrow (in other words, if you had to show a vector in a that's how you'd sketch it). Mathematically, a vector's direction is often specified by an angle. To use the example given above, "33 kph southeast" may alternatively be described as "33 kph at 45 degrees." In Flash, vectors are used primarily with physics applications. This is because multiple vectors (of the same type) can be added together to form one resultant vector. Adding vectors is called superposition. For if a balloon is floating in the air, several forces are being exerted on it simultaneously, such as force from wind, gravitational force, and a buoyant force (that is, the force that is pushing the balloon up). With three forces acting on one balloon, it might be difficult to figure out what the balloon will do. Will it rise or will it Using superposition, you can add the vectors together to find the resultant vector (and determine the next move). One vector is much easier to work with than three. Vectors can be divided up into x and y components (in this context, the word components refers to pieces). This is called resolving a vector. You already did this same thing in the "Projection" section. Resolving a is nothing more than projecting it along the coordinate system axes. To add vectors together, you must 1. Resolve all of the vectors into their x and y components. Those pieces are the remainin g two sides of the right triangle. 2. Add all of the x components together. 3. Add all of the y components together. Let's use the example we started above. Imagine a balloon in the air with three forces acting on it: z A gravitational force with a magnitude of 10 at an angle of 90° z A buoyant force with a magnitude of 8 at an angle of 270° z A wind force with a magnitude of 5 at an angle of 45° To add the vectors together (looking back at our three-step checklist above), the first step is to resolve each vector into its components. //Gravitational force angle1 = 90; magnitude1 = 10; //Buoyant force angle2 = 270; magnitude2 = 8; //Wind force angle3 = 45; magnitude3 = 5; //Resolve the vectors into their components x1 = magnitude1*Math.cos(angle1*Math.PI/180); y1 = magnitude1*Math.sin(angle1*Math.PI/180); x2 = magnitude2*Math.cos(angle2*Math.PI/180); What follows is the balloon example we've been using, written in ActionScript. will appear on the screen; this is purely a mathematical exercise to introduce you to the role of ActionScript in this process. Later in the book, after I've introduced you to the other concepts necessary to understanding them, we'll delve into many more practical examples. In the code below, I've used the number 1 appended to the ends of all variables associated with the gravitational force; 2 for the buoyant force; and 3 for the wind force. (The lines that begin with // are comment lines, for information only.) To try this ActionScript yourself, open the Actions panel in Flash and enter the ActionScript below, or open the force_example.fla file from the Chapter03 folder on the CD-ROM. y2 = magnitude2*Math.sin(angle2*Math.PI/180); x3 = magnitude3*Math.cos(angle3*Math.PI/180); y3 = magnitude3*Math.sin(angle3*Math.PI/180); Notice the Math.PI/180 factor in each line of ActionScript above. Remember that the trigonometric only work with angles measured in radians. This factor converts the angle from degrees to radians. The next two steps are to add all of the x components and y components together to form two resultant vectors: //Add the x pieces x = x1 + x2 + x3; //Add the y pieces y = y1 + y2 + y3; You now have the sum of all the forces in the x direction and the sum of all the forces in the y direction. Add these two lines of ActionScript to display the result in the output window: trace("Force in the x direction="+x); trace("Force in the y direction="+y); When you test the SWF file, you will see that the force in the y direction is 1.53. Since this number is greater than 0, the balloon will be forced to move toward the ground. The force in the x direction is 3.53. This that the balloon will be forced to move to the right. With the concepts and techniques in this chapter, you are adding practical skills to your programming You will find that these things will come in handy frequently. We will revisit vectors and explore more of vector uses in the chapters on physics and collision reactions. Still lost? There is hope! To many people, math is a dry subject. It is understandable if, when you've finished this chapter, you feel like you have grasped only part of it. Everything will make more sense when you start to see the p ractical uses of the math y ou've seen here, and the conce p ts will become more solidified in your mind. It may make sense for you to reread parts of this chapter when you start to use trigonometry in your games. I l @ve RuBoard I l @ve RuBoard Points to Remembe r z Trigonometry is the branch of mathematics that deals with the relationships between the sides and angles of triangles. z In game programming, trigonometry is used to help determine trajectories, distances, and deflection after a collision, to name a few of its functions. z Flash uses the grid-based Cartesian coordinate system to identify, place, and move objects. z By default, the registration point of a Flash movie clip is the upper-left corner of stage or movie. z The unit of measurement that Flash uses for an g les is not de g rees, but radians. You can easil y convert from one unit of measurement to the other to work in a more familiar manner. The one exception to having to use radians in Flash is when you're changing the _rotation property of a movie clip. z You can use the Pythagorean theorem to find the distance between two points. z The trigonometric functions sine, cosine, and tangent use various ratios of the triangle side lengths to determine values and, used inversely, to deliver results as angles. z A vector is a mathematical object that has both magnitude (a numeric value) and direction. For example, velocity is a vector because it has both magnitude and direction. Vectors can be divided up x and y components to project it along the axes of the coordinate system. This is called resolving a vector. I l @ve RuBoard I l @ve RuBoard Chapter 4. Basic Physics Introduction to Physics Speed, Velocity, and Acceleration Newton's Three Laws of Motion Gravity Friction Points to Remember Have you ever wondered how to add gravity to a game, Or even just how to make a movie clip move the screen? Understanding basic physical laws and how to apply them is the key to creating dynamic games. In this chapter you will learn some of the most fundamental physics concepts, such as gravity and friction, and how to apply them in Macromedia Flash using ActionScript. I l @ve RuBoard I l @ve RuBoard Introduction to Physics For some reason, there is a common fear or una pp roachable feelin g about p h y sics. When I was in colle g e and the fact that I was a physics major came up in conversation, I would inevitably get one of three odd looks. first one implied that I had just sprouted another head; the second made the person appear to have gotten a sour taste in his or her mouth; the third (my favorite) was a consoling glance that said "I am so sorry." I'm sure what caused this general feeling about physics (hey, my physics-lab buddies and I were really fun but rest assured that in this chapter we will allay those fears. Physics is the branch of science that studies and describes the behavior of objects in nature on the most fundamental level. Here are some interactions and occurrences that physics is used to describe: z An object falling to the ground (remember Isaac Newton and his apple) z The effect of an electron on a proton z Electrical current z The motion of the planets There are many fields of specialized study within physics, and some areas of physics are very difficult to Fortunately for us, Flash requires us to learn only the basics of the easiest-to-learn t yp e: classical mechanics. Classical mechanics is the one area of physics where it is easy to conceptualize what is happening, or what should happen, in a simple situation. For instance, if you have a ball on a hill, you don't need an advanced degree in science to tell you that the ball will roll down the hill—common sense should suffice. ( In other areas of physics, it can be difficult to predict what will happen just by looking at the situation.) In this chapter we will discuss the basic concepts of speed, velocity, and acceleration; Newton's laws; gravitation; and friction. We will not cover conservation of energy or of momentum until Chapter 6, "Collision Reactions." This is because we are trying to introduce topics and concepts in a somewhat linear fashion. Conservation of energy and momentum are concepts that apply after there has been a collision of objects, we have not yet reached that point. One more thing to note before we jump in: I'm going to be making some distinctions between real physics good-enough physics. Real physics concerns the motion and reactions that can be described by real physics equations. Everything initially discussed in this chapter is real physics. However, there are situations where real physics equations may be a little too intense for Flash to calculate frequently. As it turns out, they can replaced with vastly simplified equations that give good-enough results. We will discuss two of the most commonly used "good-enough" physics substitutes in the " Gravity" and "Friction" sections. I l @ve RuBoard I l @ve RuBoard Speed, Velocity, and Acceleration You may not know the difference between speed and velocity, but you probably have at least some idea of what speed, velocity, and acceleration are. In this section I'll introduce you to these concepts and point out differences between them. Speed and Velocity Velocity is a vector; speed is the magnitude of that vector. In Chapter 3, "Trigonometry 101," we introduced vectors. If you're a linear reader, this concept may be fresh in your mind. But to review, vectors are mathematical objects that contain two pieces of information: a magnitude (also called a scalar value) and a direction. For instance, the velocity 30 kilometers per hour (kph) southeast is a vector. Its magnitude (the speed) is 30, and its direction is southeast. Let's dig a little deeper into the definitions of these important concepts. Speed: The ratio of distance covered and the time taken to cover this distance. Mathematically, this is as the equation speed = distance/time. For example, if a car travels 30 kilometers in 2 hours, then its speed 30 kilometers/2 hours = 15 kilometers/hour. Velocity: A vector formed by combining speed with a direction. Now let's see how to use this concept of speed and velocity to find the distance traveled in a certain time. If we know the speed at which a car is traveling, how do we know how far it has traveled in, say, 3 hours? Above we said: speed = distance/time By doing simple algebra (multiplying both sides by time), we arrive at this equation: distance = speed*time With this equation we can find how far a car (or any object) traveled if we know its speed and the amount of time it moved. In the same way, if we know how far the car traveled and the speed of the car, then we can calculate the travel time using the final permutation of this equation: time = distance/speed Applying Speed with ActionScript So now you understand what speed and velocity are. And you understand how if you know any two of the following variables—speed, distance, or time—you can find the remaining value. In many games you are to need to program movie clips (such as a ball, a car, or a rocket ship) to move. So how do you apply speed a movie clip? You are about to find out. We have been talkin g and thinkin g about s p eed as bein g measured in units of distance/time ( distance divided by time). But Flash is not a time-based environment—it is a frame-based environment. To Flash users, one frame can be assumed to be one unit of time. So (as you'll see on your screen if all goes well), it is OK for us replace every occurrence of a time variable in equations with a variable for frames. For instance, if distance = speed*time, then the new form is distance = speed*frames. (In other words, speed is no longer 10 it's 10 units/frame.) In Flash we are going to change the definition of speed by replacing time with frames. let's look at our definition of speed again, this time with our new twist: As defined above, speed is distance divided by time. When you read "15 kilometers/hour," you say "15 kilometers per hour." [...]... ActionScript, performing a hitTest() on each balloon, determine if there are any collisions between the mouse and the balloon Here is the ActionScript used in this example 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 //Number of balloons to be created totalBalloons = 10; //Set the dimensions of the screen so that we can randomly place the balloons screenWidth = 700; screenHeight =... instance name of point_clip2 The circle has an instance name of circle_clip1 The ActionScript in this file was built to determine if a point is with a circle Here are the first 13 lines 1 2 3 4 5 6 7 8 9 10 11 12 13 //Define point 1 point1 = {}; point1.x = point_clip1._x; point1.y = point_clip1._y; //Define point 2 point2 = {}; point2.x = point_clip2._x; point2.y = point_clip2._y; //Define circle 1 circle1... netForce = force1 + force2 2 Solve for the acceleration Since netForce = mass*accel, then accel = netForce/mass Let's take a look at the ActionScript for the single movie clip in this file (in the Actions layer): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ymov = 0; mass = 1; //weight, the downward force force1 = 30; //bouyancy, the upward force force2 = -31; //total force netForce = force1 + force2; //Newton's second... using the following equations: xposition_future = xposition_now + xspeed_now*time + 1 /2* (xacceleration)*time2 and yposition_future = yposition_now + yspeed_now*time + 1 /2* (yacceleration)*time2 Applying Acceleration with ActionScript The equations you've just been looking at may seem messy, but their application in Flash is quite easy Remember that we can replace time with frames in all of our equations... iteration 12, then the name created is balloon 12 Since the value of name is "balloon 12" then the action _root[name] is equivalent to writing _root.balloon 12 This is how the references to the movie clips are created dynamically in these loops ActionScript Review: attachMovie() and Linkage Identifiers With ActionScript you can create a new instance on the stage of a movie clip that is in the Flash file's... this sounds like three items instead of read it again with careful obedience to the commas.) Acceleration = (velocity2 - velocity1)/(time2 - time1) where velocity2 is the velocity at time2, and velocity1 is the velocity at time1 The units of acceleration are measured as distance/time2 If you know the acceleration of an object and its current velocity, then you can find or project the velocity of that... specific game situations Usually these are times when the mouse is involved Simple clickdestroy–style games make use of this type of collision detection For example, let's take a balloon game If user clicks the mouse when it's positioned over a balloon, then the balloon pops This is the easiest way to out if the mouse is over a movie clip without using a button However, most click-and-destroy games are... explode Here is the ActionScript used to accomplish this 1 2 3 4 5 6 7 _root.onMouseDown = function () { mx = _xmouse; my = _ymouse; if (balloon.hitTest (mx, my)) { balloon.play(); } } In line 1 of this script we define a function that will be called when the mouse button is pressed down (and yet released) When this happens, two variables are set mx and my—to store the x and y positions of the mouse Then,... the up arrow key is pressed (As you might expect, when the down arrow key is pressed, the car decelerates.) Here is the ActionScript that accomplishes this 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 xmov = 1; ymov = 1; accel = 2; angle = Math.atan2(ymov, xmov)*180/Math.PI; car._rotation = angle; _root.onEnterFrame =function () { if(Key.isDown(Key.UP)) { xmov += accel; ymov += accel; } else if (Key.isDown(Key.DOWN))... ActionScript on frame 1 1 2 3 4 5 6 xmov = 3; ymov = 2; _root.onEnterFrame = function () { car._x += xmov; car._y += ymov; } This differs from the ActionScript in the previous example by two lines of code Line 2 defines a variable to represent the speed in the y direction, and line 5 controls the placement of the car by adding the value of to the car's y position This is done 24 times a second, so the . are: 1 11 1 angle = Math.atan2(ymov, xmov)*180/Math.PI; 2 22 2 car._rotation = angle; In short, line 1 calculates the angle that the car should be rotated, and line 2 rotates the car. Summoning. of your games. use acceleration in programming, here is what you should do. 1. Create a variable to contain the acceleration. For instance, accel = 2 accel = 2accel = 2 accel = 2 . 2. Create. the object. car._x += xmov; car._y += ymov; 1 11 1 xmov = 1; 2 22 2 ymov = 1; 3 33 3 accel = 2; 4 44 4 angle = Math.atan2(ymov, xmov)*180/Math.PI; 5 55 5 car._rotation = angle; 6 66 6

Ngày đăng: 12/08/2014, 21:20

TỪ KHÓA LIÊN QUAN

w