Microsoft XNA Game Studio Creator’s Guide- P5 ppsx

30 245 0
Microsoft XNA Game Studio Creator’s Guide- P5 ppsx

Đ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

MICROSOFT XNA GAME STUDIO CREATOR’S GUIDE 98 The vertices for the earth and moon are set when the program begins, so InitializeTriangle() is called from the Initialize() method: InitializeTriangle(); When animating the triangle, a time-scaled increment is made to the triangle’s ro- tation during each Update(). This rotation value is modded by 2π to clamp the value between 0 and 2π. earthRotation += gameTime.ElapsedGameTime.Milliseconds/1000.0f; earthRotation = earthRotation%(2.0f * MathHelper.Pi); moonRotation += (float)TargetElapsedTime.Milliseconds/750.0f; moonRotation = moonRotation %(2.0f * MathHelper.Pi); Here are the five recommended steps for drawing the revolving Earth object: 1. Declare the matrices. 2. Initialize the matrices. The identity matrix is initialized as a default matrix in the event of no transformations. (Try leaving it out of the transformation, FIGURE 7-2 Earth and moon example 99 and notice you still get the same result.) A matrix that generates the earth’s revolution on the Y axis is computed based on a constantly changing angle (in radians). Every frame, the angle is incremented with a value based on the time lapse between frames. This time-scaled increment to the rotation angle ensures that the animation appears smoothly while maintaining a constant rate of change. Scaling the increment based on time is necessary because durations between frames can vary depending on other tasks being performed by the operating system. Finally, a translation is created to move the earth 0.5 units upward on the Y axis and 8.0 units inward on the Z axis. 3. The World matrix is built by multiplying each of the matrices in the transformation using the I.S.R.O.T. sequence. 4. The World matrix used to transform the earth is passed to the shader as part of the World*View*Projection matrix. 5. The triangle is rendered by drawing vertices with a triangle strip. Adding DrawEarth() to the game class provides the code needed for transform- ing and drawing the Earth: private void DrawEarth(){ // 1: declare matrices Matrix world, translation, rotationY; // 2: initialize matrices rotationY = Matrix.CreateRotationY(earthRotation); translation = Matrix.CreateTranslation(0.0f, 0.5f, -8.0f); // 3: build cumulative World matrix using I.S.R.O.T. sequence // identity, scale, rotate, orbit(translate & rotate), translate world = rotationY * translation; // 4: set shader parameters positionColorEffectWVP.SetValue(world * cam.viewMatrix * cam.projectionMatrix); // 5: draw object - select primitive type, vertices, # primitives PositionColorShader(PrimitiveType.TriangleStrip, triangleVertex, 1); } CHAPTER 7 Animation Introduction MICROSOFT XNA GAME STUDIO CREATOR’S GUIDE 100 Next, the DrawMoon() method implements the same five-step drawing routine to transform and render the same vertices as a Moon object. The moon has its own revo- lution about the Y axis, and it also orbits around the earth. In addition, the moon is scaled to one-fifth the size of the earth. The DrawMoon() method performs all of the same transformations as the DrawEarth() method. Plus, DrawMoon() implements scaling and an orbit. All of the matrices declared in the DrawEarth() method are declared in DrawMoon() to perform the same transformations. Also, additional matrices are declared and set in this method to handle the scaling and orbit. The scale is set to draw the object at one-fifth the size of the earth by assigning the scale matrix the following value: Matrix.CreateScale(0.2f, 0.2f, 0.2f); Remember that the orbit is a two-step process that involves a translation followed by a rotation. When the World matrix is built, the crucial I.S.R.O.T. sequence is used to ensure that the matrices are multiplied in the proper order: world = scale * rotationY * orbitTranslation * orbitRotationY * translation; Since the same vertices are used for drawing the Moon and the Earth, steps 4 and 5 of DrawMoon() are identical to those in DrawEarth(). private void DrawMoon(){ // 1: declare matrices Matrix world, scale, rotationY, translation, orbitTranslation, orbitRotationY; // 2: initialize matrices scale = Matrix.CreateScale(0.2f, 0.2f, 0.2f); rotationY = Matrix.CreateRotationY(moonRotation); translation = Matrix.CreateTranslation(0.0f, 0.8f,-8.0f); orbitTranslation = Matrix.CreateTranslation(0.0f, 0.0f,-1.0f); orbitRotationY = Matrix.CreateRotationY(moonRotation); // 3: build cumulative World matrix using I.S.R.O.T. sequence // identity, scale, rotate, orbit(translate & rotate), translate world = scale * rotationY * orbitTranslation * orbitRotationY * translation; 101 CHAPTER 7 Animation Introduction // 4: set the shader parameters positionColorEffectWVP.SetValue(world * cam.viewMatrix * cam.projectionMatrix); // 5: draw object - select primitive type, vertices, # of primitives PositionColorShader(PrimitiveType.TriangleStrip, triangleVertex, 1); } Both the DrawEarth() and DrawMoon() methods are called from the Draw() method in the game class: DrawEarth(); DrawMoon(); When you compile and run this code, it will show the earth as a revolving triangle being orbited by a revolving moon (refer to Figure 7-2). Spend the time you need to ensure that you understand transformations. It is not an overly complex topic, but it can be challenging for beginner graphics programmers who do not give transformations the learning time the topic deserves. You will enjoy the rest of the book more when you have mastered this introduction to animation. Be fearless when experimenting with your transformations. When you test and run your projects, you will probably know right away if your transformations are working properly. Of course, use the documentation presented in this section as a guide to understanding the topic. The real learning will happen when you try to cre- ate your own transformations. C HAPTER 7 REVIEW EXERCISES To get the most from this chapter, try out these chapter review exercises. 1. Implement the step-by-step example presented in this chapter, if you have not already done so. 2. Using primitives, create a stationary airplane with a rotating propeller that is made from triangles, as in the following illustration. When initializing the vertices that store the propeller, be sure to center the X, Y, and Z coordinates around the origin. Failure to center the X, Y, and Z coordinates of your surface about the origin will offset your rotations and will lead to strange results when unbalanced objects are transformed (see Figure 7-3). 3. When you finish Exercise 2, transform your propeller so it serves as a rotor for a helicopter. Using the same set of vertices, write another procedure to transform and render the same rectangle used for the main rotor as a back rotor, as shown here in Figure 7-4. MICROSOFT XNA GAME STUDIO CREATOR’S GUIDE 102 FIGURE 7-3 Primitive airplane with rotating propeller FIGURE 7-4 Helicopter with top and back rotors using the same vertices CHAPTER CHAPTER 8 8 Character Character Movement Movement 104 AFTER reading and applying the material covered in Chapter 7, you should be comfortable performing simple animations with translations and rotations. For most gamers, it is not enough just to make a bird flap its wings or make the propeller of an airplane spin; anybody with half an ounce of curiosity wants to see these objects actually fly. This chapter introduces a simple animation method that allows moving objects to travel independently within your 3D world. Additional methods for enabling the movement of objects are covered in Chapter 21. Regardless of the method used to move objects and characters, basic movement is generated by updating the X, Y, and Z position coordinates, as well as the rotation angles of the moving object rendered at every frame. D IRECTION When you animate vehicles that fly, drive, sail, or glide, you most likely expect them to point in the direction they are traveling. Calculating the angle of direction can be done using several methods. Without this calculation, your vehicles could look as if they are flying backward or even sideways. Trigonometry offers a simple intuitive approach to calculate the angle of direction—this method will be used often through- out this book. However, computing direction can also be done with vectors. Using vectors to calculate direction is actually a more powerful method for implementing rotations of direction because they offer a simpler means to implement complex transformations for directions in all planes. Calculating Direction Using Trigonometry The trigonometry applied in this chapter is actually quite simple and only involves using the arctangent function. The arctangent function enables calculations of direc- tion about the Y axis when the X and Z coordinates of the object are known. When the Right Hand Rule is used, all positive rotations are counterclockwise. To calculate an object’s angle about the Y axis, draw a line from the object’s position to the preceding axis in the rotation to create a right-angle triangle. The tangent of the angle between the hypotenuse and the axis can be calculated with the following equa- tion: tan φ side length / adjacent side length (where φ is the angle) 105 This equation can be rearranged to isolate the angle: φ = tan –1 (opposite / adjacent) φ = atan (opposite / adjacent) Figure 8-1 shows the angle about the Y axis in relation to the hypotenuse, oppo- site, and adjacent sides of the right-angle triangle. Calculating Direction Using Speed When Y is constant, the change in X and Z, during each frame, measures speed. On a three-dimensional graph, the X and Z speed combination will always fall in one of four quadrants, depending on whether each of the X and Z speeds is positive or negative. Calculating Direction Using the Math.Atan() Function To calculate the angle of direction about the Y axis, create an imaginary right-angle triangle by drawing a line from the X, Z coordinate to the preceding X or Z axis. This line must be perpendicular to the X or Z axis. You can use XNA’s Math.Atan() function to compute the angle of rotation about the Y axis using the corresponding X and Z values as opposite and adjacent parameters: double radians = Math.Atan( (double)opposite/(double)adjacent ); CHAPTER 8 Character Movement FIGURE 8-1 Hypotenuse, opposite, and adjacent sides of a right-angle triangle The Math.Atan() function then returns the angle of rotation about Y for the im- mediate quadrant. An offset that equals the total rotation for the preceding quad- rants is added to this angle to give the total rotation in radians. Figure 8-2 illustrates the relationship between the X and Z speeds for each quadrant and their offsets. When the Math.Atan() function is used, each quadrant uses a slightly different equation to generate the rotation about the Y axis. These individual quadrant equa- tions are summarized in Table 8-1. Understanding this basic trigonometry can help you develop algorithms to gener- ate your own direction angles. MICROSOFT XNA GAME STUDIO CREATOR’S GUIDE 106 FIGURE 8-2 Calculating angle of direction about the Y axis using speed quadrants Quadrant Offset Equation 10 Math.Atan (-z/x) 2 /2 Math.Atan (-x/-z) + /2 3 Math.Atan (z/–x) + 43/2 Math.Atan (x/z) + 3 /2 Quadrant Equations to Calculate the Angle of Direction About the Y Axis TABLE 8-1 107 CHAPTER 8 Character Movement Calculating Direction Using the Math.Atan2() Function Thankfully, there is an easier way to employ trigonometry to calculate the angle of direction about the Y axis. The Math.Atan2() function eliminates the need to fac- tor quadrant differences into the calculations. To compute the angle of rotation about the Y axis with the Math.Atan2() function, the calculation becomes this: double radians = Math.Atan2((double) X / (double) Z) This equation can be used to calculate the angle of direction about the Y axis for all quadrants. Both the Math.Atan() and Math.Atan2() functions will be demonstrated in the example presented in this chapter. Calculating Direction Using Vectors Calculating direction using vectors is the more powerful method. The math behind implementing vectors of direction is explained in more detail later, in Chapters 15, 16, and 17, so you may choose to read these chapters first for a better understanding of how the vectors work. The vector logic for calculating direction is being presented ahead of these chapters to ensure you have a better way to move your vehicles, ves- sels, and aircraft through your 3D world. The vectors that describe the orientation of a moving object can be summarized using the Look, Up, and Right vectors. These vectors describe the moving object’s direction and uprightness (see Figure 8-3). The Look vector, also known as the Forward vector, is calculated from the differ- ence in the view position and the position of the object. When you are animating ob- jects, the Look vector could also be the same as the object’s speed vector. The Up vector describes the upright direction. For most objects that are animated in this book, the starting upright direction is 0, 1, 0. When we stand on our own two feet, we have an Up vector of 0, 1, 0. The Right vector describes the perpendicular from the surface created by the Up and Look vectors. The Right vector can be used for a strafe in addition to assisting with the computation of angles of direction. If the Up vector is known, the Right vector can be calculated using the cross prod- uct of the Look and Up vectors. The Right vector equals the cross product of the Up and Look vectors. [...]... PositionColorShader(PrimitiveType.TriangleStrip, propellerVertices, 2); } 113 Character Movement C H A P T E R 114 MICROSOFT XNA GAME STUDIO CREATOR’S GUIDE Both DrawAirplaneBody() and DrawPropeller() are called from the Draw() method where all drawing for your game application is triggered: DrawAirplaneBody(); DrawPropeller(gameTime); When you run this code, a stationary airplane body and a propeller that rotates on the... previous one for animation, you will have more control over the look and feel of your game Being 117 Character Movement C H A P T E R 118 MICROSOFT XNA GAME STUDIO CREATOR’S GUIDE able to control the movement of your vehicles, objects, and other beings will lead to many interesting avenues for creating great graphics effects and game play C HAPTER 8 REVIEW EXERCISES To get the most from this chapter, try out... the same directory as the C# source files The syntax shown here is used to load an image from the game project’s Images folder within the project’s Content node: Texture2D texture = Content.Load("Images\\imageName"); 121 Texturing Your Game World C H A P T E R 122 MICROSOFT XNA GAME STUDIO CREATOR’S GUIDE Vertex Types for Textures Previous examples used a VertexPositionColor variable for... vertex shader only enabled vertices for color and position For textures, the vertex shader input and output must be declared to handle not only position and 123 Texturing Your Game World C H A P T E R 124 MICROSOFT XNA GAME STUDIO CREATOR’S GUIDE color but also UV coordinate data The following struct defines the structure of each vertex that is passed to the vertex shader: struct VSinput{ float4 position... shade the texturized pixel // with color to give your textures a tint Do this by multiplying // output by the input color vector OUT.color *= IN.color; } 125 Texturing Your Game World C H A P T E R 126 MICROSOFT XNA GAME STUDIO CREATOR’S GUIDE // the shader starts here technique TextureShader{ pass p0{ // texture sampler initialized sampler[0] = (textureSampler); // declare and initialize vs and ps... this example simple, the airplane is built with nothing more than a triangle for the body and a spinning rectangle for the propeller (see Figure 8-4) 109 Character Movement C H A P T E R 110 MICROSOFT XNA GAME STUDIO CREATOR’S GUIDE FIGURE 8-4 Airplane animation If you want, you can easily swap these primitive objects with 3D models; the sequence of instructions to create the transformation for the animation... airplane is drawn as a stationary object A translation matrix generated by the instruction: translation = Matrix.CreateTranslation(0.0f, 0.75f, -8.0f); 111 Character Movement C H A P T E R 112 MICROSOFT XNA GAME STUDIO CREATOR’S GUIDE moves the plane in a one-time translation 0.75 units up the Y axis and -8.0 units inward along the Z axis A slight rotation is generated with this instruction: rotationY =...108 MICROSOFT XNA GAME STUDIO CREATOR’S GUIDE FIGURE 8-3 Direction vectors When these vectors are normalized, or scaled so their lengths range between -1 and 1, they can be used in a matrix that calculates the direction... quadrants to calculate the angle of rotation about the Y axis: float RotationAngle(){ float PI = MathHelper.Pi; float rotationY = 0.0f; // 1st quadrant 115 Character Movement C H A P T E R 116 MICROSOFT XNA GAME STUDIO CREATOR’S GUIDE if (speed.X >= 0.0f && speed.Z . MICROSOFT XNA GAME STUDIO CREATOR’S GUIDE 98 The vertices for the earth and moon are set when the program begins,. primitives PositionColorShader(PrimitiveType.TriangleStrip, triangleVertex, 1); } CHAPTER 7 Animation Introduction MICROSOFT XNA GAME STUDIO CREATOR’S GUIDE 100 Next, the DrawMoon() method implements the same five-step drawing. same rectangle used for the main rotor as a back rotor, as shown here in Figure 7-4. MICROSOFT XNA GAME STUDIO CREATOR’S GUIDE 102 FIGURE 7-3 Primitive airplane with rotating propeller FIGURE 7-4 Helicopter

Ngày đăng: 02/07/2014, 06:20

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan