Create xNa shooter games-integrate them

Source: Internet
Author: User

Integrated

In the first two chapters, you have seen some xNa shooterCodeFragment. Before you start, you need all the files of the xNa shooter project, which should be created first. This project requires the sound effects of all xact projects, as well as shader, font textures, tests, menus, and so on. Finally, after adding the. x 3D model and texture file, you can continue and test it through unit tests in the txeture, shader, and model classes.

After performing the following operations, figure 11-1 shows a new project named xNa SHOOTER:

    • Create a new windows xNa game project named "xnashooter"
    • Drag allSource codeFile. Because it is not required in xnashooter, the following files are deleted and sorted by namespace:

      • Game namespace: asteroid. CS, baseasteroidmanager. CS, gameasteroidmanager. CS, level. CS, physicsasteroidmanager. CS, smallasteroid. CS, and spacecamera. CS
      • Gamescreens namespace: Help. CS, missionselection. CS and options. CS
      • Graphics namespace: animatedmodel. CS and lensflare. CS

      • Shaders namespace: parallaxshader. CS and prescreenskycubemapping. CS
    • Game1.cs was also removed, and the rocketcommandergame class was renamed as xnashootergame.
    • Replace the rocketcommanderxna namespace used in all files with the xnashooter namespace.

    • Most of the Code in mission. CS, player. CS, mainmenu. CS, and xnashootergame. CS is commented out to compile the project.


Figure 11-1

Sound

Source code is important, but there is no texture, sound and 3D models you cannot complete a real game. Since the xnashooter xact project has been discussed in Chapter 9th, this will be the first thing added to the new project. The only file in the project to be added is the xnashooter.xapfile, which can contain many. wav files. I want to add all .wav files to the project because I want to see which files are directly used for this project.

After the xact project is added to the sounds namespace, you can change the sound class and test all the sounds through testplaysounds. This unit test does not cover all sounds, but the most important sound effects are tested. Gaming music and Explosion Sound use more than one sound file. This means that when you play an explosion, one of the three explosion sound files will be randomly selected and played. This requires no special code, and everything is set in xact.

Public static void testplaysounds () {testgame. start (delegate {If (input. mouseleftbuttonjustpressed | input. gamepadajustpressed) sound. play (sounds. defeat); else if (input. mouserightbuttonjustpressed | input. gamepadbjustpressed) sound. play (sounds. victory); else if (input. keyboardkeyjustpressed (keys. d1) sound. play (sounds. gamemusic); else if (input. keyboardkeyjustpressed (keys. d2) sound. play (sound S. enemyshoot); else if (input. keyboardkeyjustpressed (keys. d3) sound. play (sounds. EXPLOSION); else if (input. keyboardkeyjustpressed (keys. d4) sound. play (sounds. health); else if (input. keyboardkeyjustpressed (keys. d5) sound. play (sounds. plasmashoot); else if (input. keyboardkeyjustpressed (keys. d6) sound. play (sounds. mgshoot); else if (input. keyboardkeyjustpressed (keys. d7) sound. play (sounds. gattlinsh- OOT); else if (input. keyboardkeyjustpressed (keys. d8) sound. play (sounds. EMP); texturefont. writetext (2, 30, "press 1-8 or a/B or left/right mouse buttons to play back" + "sounds! ") ;}) ;}// Testplaysounds ()
User Interface

Now render the user interface and menu texture. Screenshot) to check the game's screen logic (see Figure 11-2 ). Implementing the main menu and other game screens does not take much time. They are very similar to rocket Commander, but some complex screens such as option and misson selection are removed because xnashooter does not need them.

Figure 11-2

You have learned the xnashooter game interface, but the entire game logic will be discussed at the end of this chapter. You only have three game screens, which are easy to implement. The Main Menu displays four buttons to add a new game screen to the stack, so that you can jump out of the new game screen and return to the main menu. Highscore is the lite version of highscore in the rocket Commander. Because it does not support the network, only the highscore of the local machine is displayed. The credit screen displays several lines of text and adds the back button.

Quickly browse the run method of mainmenu, which processes the main menu and the four buttons that enter other screens:

// Render backgroundgame. rendermenubackground (); // show all buttonsint buttonnum = 0; foreach (menubutton button in menubuttons) // don't render the back button if (button! = Menubutton. back) {If (game. rendermenubutton (button, buttonlocations [buttonnum]) {If (Button = menubutton. missions) game. addgamescreen (new mission (); else if (Button = menubutton. highscore) game. addgamescreen (New highscores (); else if (Button = menubutton. credits) game. addgamescreen (new credits (); else if (Button = menubutton. exit) Quit = true;} // If buttonnum ++; If (buttonnum> = buttonlocations. length) break;} // foreach if // hotkeys, M = mission, H = highscores, c = credits, ESC = quitif (input. keyboardkeyjustpressed (keys. m) game. addgamescreen (new mission (); else if (input. keyboardkeyjustpressed (keys. h) game. addgamescreen (New highscores (); else if (input. keyboardkeyjustpressed (keys. c) game. addgamescreen (new credits (); else if (input. keyboardescapejustpressed) Quit = true;
Texture

In addition to menu texture, mouse texture, and font texture, you need more textures. First, you have seen the hudtexture and the new numbersfont.png texture in the previous chapter. The numbersfont.png texture allows you to display colored numbers on the top of the HUD. There are also many effects textures used in the special effect system, which will be discussed later in this chapter. It is difficult to explain which texture is used in the game. See figure 11-3, which briefly explains the purpose of each texture.

Figure 11-3

All textures must be added to the project, but the settings of the content importer are different. For example, the mouse, main menu, and font textures should not be compressed into dxt format (files using DDS), they are still in Uncompressed 32bpp (the number of bits per pixel) format, however, other materials, such as explosion effects, need to be compressed to make them smaller. For example, the bigexplosion effect consists of about 30 textures of 128x128. If no compression is performed, an explosion will take about 2 MB.

By using dxt5 compression, you can reduce it to 0.5 Mb, which allows you to perform several explosions and save disk and video storage space. To support alpha channels, dxt5 compression format should be used instead of dxt1, although dxt1 is compressed less.

The game has a texture of about 3 MB, of which 1 MB is used for two explosions, and 1 MB is used for menus. Others are used for visual effects, Hud, and font. The special effect system is very complicated. Through the interaction of particles, it achieves a cool explosion effect. Sometimes special effects are integrated with physical engines, allowing particles, smoke, and explosions to interact with the surrounding environment or itself.

For xnashooter, a simple special effect system is enough. Although special effects are difficult to write, they are easy to change or add new special effects to textures. You only need to add an add method and use testeffects in the effectmanager class to perform a unit test.

3D Model

This game uses a large number of 3D models (see Figure 11-4 ). I initially used only one ship model and some special effects, but soon I found that there were not at least three to four different enemies, and the game would become boring. The behavior of these enemies varies greatly in xNa SHOOTER:

    • The ownship model is your own ship. You can launch mg, plasma, Gatling-gun, or rocket. You can also launch an EMP bomb to kill all enemies on the screen. Your flight is the fastest in the game, but if the screen is full of enemies, it will not help you. you must first kill them before the enemy shoots you down.
    • Corvette is the most basic enemy. It emits mg from both sides of the left and right, its life is not high, and its weapons are not strong. The main advantage is that if you are in the shooting direction, you will be immediately hit. If you do not destroy them in time and the screen is full of Corvette, you will lose your life.

    • A small transport ship is a small ship that carries items. 25% to 50% may contain some useful items, especially the values of life, which are useful when your life is low. Shooting them down may also result in an EMP bomb. The transport ship also carries other items, allowing you to switch weapons. Transport ships do not launch weapons, but you should avoid collision with them. The life of a small transport ship is lower than that of Corvette.
    • Firebird is a very powerful enemy, and they send fireballs directly to you. It can calculate your current position and force you to dodge fireballs constantly. It has a larger life value than other smaller ships. Do not hit Firebirds, which greatly reduces the life value. If there are too many Firebirds on the screen, only EMP bombs can help you.
    • Rocket-frigate is the largest ship in the game. I originally wanted to create a boss at the end of the game, but it takes too much time to create a 3D model and implement the game logic. If you are really interested in the shooting game, adding boss and more levels should not be difficult. Rocket-frigate launches a rocket similar to yours, but it is much smaller and will not cause great damage. Aside from heavy armor and high lifetime, this enemy's main advantage is that the rocket is capable of tracking and will keep tracking your ship until it consumes fuel. If you are proficient in operations, it is not difficult to deal with a rocket-frigate and still hit it, but it is much harder to deal with multiple rocket-frigate at the end of the service. Make sure you have a heavy weapon or EMP bomb to handle this situation.

    • It's not a real enemy. They just float around you to stop you from acting. They cannot be shot, but the collision will lose a lot of life values. It is difficult for common weapons to destroy them, but EMP bombs can destroy them all. You may have noticed that I borrowed the Minor Planet model from the rocket Commander.

Figure 11-4

These enemies are very important to the game, but they will lose a lot of fun without any props, and will look boring without any background scenes. The item can return the life value, supplement the EMP bomb or change one of the four weapons: Mg, plasma, Gatling-gun, and rocket launcher.

Background objects do not interact with the game, but are placed on the background and shadow. First, the landscapebackground. x model is rendered and repeated in the level. Later in this chapter, you will learn how to create and create checkpoints. After the landscapebackground. x model is rendered, buildings and plants are rendered on it. Because the scene is a valley with the same height in the middle, you can easily add buildings and plants. All objects are randomly added and generated. You can also add more objects. It is very easy to change the scene model list. You only need to add another model, which is automatically generated on the ground.

Animated texture

You have used animated textures in the rocket Commander, but you have never learned how to implement them. First, you need a set of textures that can be changed at a speed of 1/30 seconds. There are two sets of animated textures in xNa shooter to achieve two explosion effects. You only need to load 30 textures for each blast effect and process them. Because you need this code more than once, you should abstract it to a new class: animatedtevaxture (see Figure 11-5 ).

Figure 11-5

The constructor of the animatedtexture class is very similar to that of the texture class, but you still need to check the texture through the texture file name. Explosion effects use continuous texture names, such as bigexplosion0001.dds, bigexplosion0002.dds, bigexplosion0003.dds, and so on. The Code in the following constructor is used to load all these file names into the internal xnatextures list. Note that the DDS file is loaded in the initial version of the rocket Commander code (managed DirectX), but should be compiled into xNa. xNb file, which is the only way to load textures on the Xbox 360 platform (direct loading of DDS files is still supported on Windows ).

// OK, now load all other animated textureslist <xnatexture> animatedtextures = new list <xnatexture> (); animatedtextures. add (internalxnatexture); int texnumber = 2; while (file. exists (filenamefirstpart + texnumber. tostring ("0000") + ". xNb ") {animatedtextures. add (basegame. content. load <texture2d> (filenamefirstpart + texnumber. tostring ("0000"); texnumber ++;} // while (file. exists) xnatextures = animatedtextures. toarray ();

With the help of the select method, you can select any loaded texture. The other parts of this class are exactly the same as those of the texture class. This means you can select a texture and display it on the screen, because the internal xnatexture variable is allocated with the correct texture, you can also implement the shader for the texture. You can also directly call getanimatedtexture to access any animated texture.

/// <Summary> /// select this animated texture as the current texture // </Summary> /// <Param name = "animationnumber"> Number </param> public void select (INT animationnumber) {If (xnatextures! = NULL & xnatextures. length> 0) {// select new animation number internalxnatexture = xnatextures [animationnumber % xnatextures. Length];} // If} // select (Num)
Billboards

Now you have all the xNa shooter content, but you still need to think about how to display it. You do not have any code to render scenes, objects, and new special effects. In the rocket Commander, you only need to display the unique special effect of explosion. It does not seem convincing to put all the special effects directly on the screen in your new game. In 3D scenarios, displaying special effects in the form of polygon has the following advantages:

    • You do not have to calculate two-dimensional positions and sizes for each 3D effect. When using 3D polygon, they are converted to the screen like other things.
    • With the aid of depth buffering, the special effects can be displayed at the front and back of the object. In this way, the lighting and smoke effects after the spacecraft engine can be displayed normally even when other parts or other 3D objects are in front of the spacecraft.
    • If you sort special effects, you can use Alpha to combine them. In this way, many special effects can be combined to produce better 3D effects.

To display 3D effects directly on the screen, we usually use the billboard technology. The billboard uses a 3D square (two triangles) to display textures. Sometimes special graphics card functions, such as Dot genie, can also be used. You can see the billboard in any situation. For other 3D polygon, if they are in the wrong direction, you cannot see them or they become distorted and smaller (see Figure 11-6 ).

Figure 11-6

This is good for some special effects. For example, a 3D explosion ring is correct on the front side, but it almost disappears from both sides of the 90 degree angle. Most of the effects are poor. The effects of explosion, lighting, flame, and plasma are captured from the front, but they are similar in other directions. For example, the fireball effect should be a sphere in all directions and should not be distorted, become smaller or disappear. To achieve this, you must ensure that you can always see the special effect, that is, always convert the special effect polygon to the observer-oriented direction. The billboard class can help you implement this task (see Figure 11-7 ).

Figure 11-7

The most important method in the billboard class is render, which adds the billboard to the billboard list and renders the list when calling the renderbillboards method at the end of each frame. The render method has six overload methods, but you can also call the renderonground method to render the billboard to the XY plane. An overload method in render also allows you to specify the right and upper vectors. In this way, you can adjust the explosive ring of the spacecraft explosion at will, and add other explosive effects.

Before you view the render method, let's take a look at the unit test of the billboard class. It shows how to use this class:

Billboard. render (plasma, new vector3 (-40366f, 0.0f, 0.0f), 5.0f, basegame. totaltimems * (float) math. PI/1000.0f, color. white); billboard. render (fireball, new vector3 (-40366f, + 50366f, 0.0f), 5.0f, 0, color. white); billboard. renderonground (Ring, new vector3 (-250000f, 0.0f,-1000000f), 5.0f, 0, color. white, vecgroundright, vecgroundup); // etc. // render all billboards for this framebillboard. renderbillboards ();

In the render method, vecright and vecup vectors are used to build billboard polygon. These vectors can be extracted directly from the currently used video matrix. With the help of the basegame class, it is easy to extract these vectors. With the calcvectors auxiliary method, these operations are automatically completed in renderbillboards.

/// <Summary> /// calc vectors for billboards, will create helper vectors for // billboard rendering, shocould just be called every frame. /// </Summary> Public static void calcvectors () {// only use the inverse view matrix, world matrix is assumed to be // idendity, simply grab the values out of the inverse view matrix. matrix invviewmatrix = basegame. inverseviewmatrix; vecright = new vector3 (invviewmatrix. m11, invviewmatrix. m12, invviewmatrix. m13); vecup = new vector3 (invviewmatrix. m21, invviewmatrix. m22, invviewmatrix. m23);} // calcvectors ()

Quick View of the render method in the billboard class:

/// <Summary> /// render 3D billboard into scene. used for 3D effects. /// this method does not support rotation (it is a bit faster ). /// </Summary> /// <Param name = "Tex"> Texture used for rendering </param> /// <Param name = "lightblendmode"> blend mode this effect </param> /// <Param name = "POS"> position in world space </param> /// <Param name = "size"> size in world coordinates </param> // <Param name = "col"> C Olor, usually white </param> Public static void render (xnatexture Tex, blendmode lightblendmode, vector3 POs, float size, color col) {// invisible? If (Col. A = 0) return; texturebillboardlist texbillboard = gettexturebillboard (Tex, lightblendmode); vector3 VEC; int Index = texbillboard. vertices. count; VEC = POS + (-vecright + vecup) * size); texbillboard. vertices. add (New vertexpositioncolortexture (VEC, Col, new vector2 (0.0f, 0.0f); VEC = POS + (-vecright-vecup) * size); texbillboard. vertices. add (New vertexpositioncolortexture (VEC, Col, new vector2 (0.0f, 1.0f); VEC = POS + (vecright-vecup) * size); texbillboard. vertices. add (New vertexpositioncolortexture (VEC, Col, new vector2 (1.0f, 1.0f); VEC = POS + (vecright + vecup) * size); texbillboard. vertices. add (New vertexpositioncolortexture (VEC, Col, new vector2 (1.0f, 0.0f); texbillboard. indices. addrange (new short [] {(short) (index + 0), (short) (index + 1), (short) (index + 2), (short) (index + 0), (short) (index + 2), (short) (index + 3),}) ;}// render (Tex, POs, size)

as you can see, four vertices are constructed and added to the vertex list. Each texture and light blending mode is integrated into their respective texturebillboardlist. The two polygon indexes that make up the Quadrilateral screen are added to the index list. Vertices and index buffers in texturebillboardlist are rendered together with textures and shader in the renderbillboards method.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.