XNa framework basics-starting from scratch

Source: Internet
Author: User
Start from scratch

You have prepared everything. Now let's start coding! In this section, you will create a simple game project with the help of the xNa studio template, and then add a fewCodeTo implement some small functions. After learning the spritebatch class in the next section, you will create your first game.

Your first project

Open xNa game studio Express, select "File> New Project" in the menu bar, select the "Windows game" template in the new window that appears, and enter the name of the new project in the Project Name field, for example, "helloworld" or use the default name "windowsgame1", enter the location where the new project is saved, and click "OK. In addition, you can create game projects based on the starter kit, such as "Spacewar windows Starter Kit ". As shown in figure 1-10:


Figure 1-10

The newly created project contains two class files: game1.cs and program. CS. The program. CS file contains the application.ProgramThe main method is as follows:

 
Using (game1 game = new game1 () {.. game. Run ();} // using

The game1.cs file contains the class game1 (inherited from the class Microsoft. xNa. Framework. Game). It contains three methods mentioned earlier: Initialize, update, and draw. The initialize method does not perform any operations at this time, but calls the initialize method of the base class to perform basic initialization operations. The update method mainly contains the following lines of code to check whether the "back" button on gamepad is pressed. If you press the button, the system will exit the game. Otherwise, the system will call the update method of the base class:

// Allows the game to exitif (gamepad. getstate (playerindex. One). Buttons. Back = buttonstate. Pressed) This. Exit ();

The draw method is used to set the background color of the game window to a specific color, as shown below:

 
Graphics. graphicsdevice. Clear (color. cornflowerblue );
Press F5 to run

Press the F5 key on the keyboard, or select the debug> start debugging command on the menu bar to run the game. The window shown in 1-11-(1) is displayed, the blue background is set in the draw method.


Figure 1-11

You can also change the background color to green, such as color. Green, and then press F5 to run the program. The window shown in 1-11-(2) is displayed. The Code is as follows:

 
Graphics. graphicsdevice. Clear (clearoptions. depthbuffer, color. Green, 1, 0 );

The default value of clearoptions is clearoptions. Target | clearoptions. depthbuffer, indicating that the background color and depth cache are cleared.

Modify code

Now, you can think about how to modify your code to perform some operations. For example, you can press the Escape key on the keyboard to exit the game. Previously, xNa checks whether the back button on the Xbox 360 controller is pressed down in the update method to determine whether to exit the game. The Code is as follows:

// Allows the default game to exit on Xbox 360 and windowsif (gamepad. getstate (playerindex. One). Buttons. Back = buttonstate. Pressed) This. Exit ();

In Chapter 3-helper classes, you will learn how to use the input class, but now you can use a quick way to operate the keyboard, the following code demonstrates that you can exit the program when you press the Escape key:

 
// Get current gamepad and keyboard statesgamepadstate gamepad = gamepad. getstate (playerindex. one); keyboardstate keyboard = keyboard. getstate (); // back or escape exits our game on Xbox 360 and windowsif (gamepad. buttons. back = buttonstate. pressed | keyboard. iskeydown (keys. escape) This. exit ();

Chapter 2 will discuss sprites in detail, but now you can learn how to load images in the game a little in advance: Add a background image to the game, and then operate the keyboard or gamepad to move the background image, like in a racing game or tile engine, these are often used in many 2D role-playing games. For more complex tile engines, you also need texture such as stone, grass, water, and dirt, and even add some transition textures between grass and water ). This requires more texture and custom code, but it is not very difficult. If you are really interested in the tile engine, you can find a lot of relevant information on the network.

The texture1-12 added in your first project is shown in:


Figure 1-12

To add this texture(citygroundsmall.jpg) to your project, you only need to drag it to your project in Solution Explorer, right-click the file to view "properties", as shown in figure 1-13:


Figure 1-13

Generally, you may only see the "build action" and "Copy to output directory" Options (for example, you may want. DLL or. XML file ). However, if xNa studio detects the supported content file format, you will also see some advanced attributes. At this time, there will be three other important settings: Resource Name (Asset name) content importer and content processor ). The resource name will be used for loading resources in the future, and the Resource Name of the content file must be unique and cannot be repeated. You can select "texture-xNa framework" or. for files of the X type, select "Model importer" or. select "effect importer" for an FX file, as shown in figure 1-13-(2.

Optional) You can select "texture (sprite, 32bpp)-xNa framework" or "texture (model, dxt, mipmapped)-xNa framework ". Dxt is a compression format, which is often used in DDS files. In the game, this format is very good for texture, because its compression ratio is as high as (if it contains transparent pixels, it is), which means that you can store up to 6 times the size of texture in the same disk and video card memory. Generally, do not compress 2D sprite because using 32bpp (bits per pixel) to check their actual sizes ensures the best quality. Content About the content pipeline will be discussed later in this section.

Now, if you press F5 or F6 to generate a solution, the added texture will be processed and a new file "citygroundsmall" will be generated in the output folder of the project. xNb, and the following information is displayed in the project output window:

 
Building citygroundsmall.jpg-> bin \ x86 \ debug \ citygroundsmall. xNb

The last thing you need to do now is to load the imported texture file, operate in the initialize method, and add a variable backgroundtexture to the class, use the previously specified Resource Name (Asset name) (the default resource name is the name of the content file you added ). To render your texture to the output screen, you need the spritebatch class to be discussed in the next chapter. It sets alpha blending and then draws texture to Sprite, finally, draw everything on the screen. The Code is as follows:

 
Texture2d backgroundtexture; spritebatch sprites; protected override void initialize () {backgroundtexture = content. load <texture2d> ("citygroundsmall"); sprites = new spritebatch (graphics. graphicsdevice); base. initialize ();} // initialize ()

To display the background, you must start spritebatch in the draw method and render texture to sprites:

Protected override void draw (gametime) {graphics. graphicsdevice. clear (color. green); sprites. begin (); sprites. draw (backgroundtexture, vector2.zero, color. white); sprites. end (); base. draw (gametime);} // draw (gametime)

The above code will display the background at the (0, 0) Coordinate of your output screen. The color parameter in the spritebatch. Draw method can also be reset, but this is not important for the time being. Press F5 and you will see the results shown in Figure 1-14:


Figure 1-14

The last thing you do for your project is to add the scroll background function using the keyboard or gamepad, so that you can render the scroll tile to the entire background. You can modify the update method as follows to capture the keyboard or gamepad input:

Float scrollposition = 0; protected override void Update (gametime) {// get current gamepad and keyboard States gamepadstate gamepad = gamepad. getstate (playerindex. one); keyboardstate keyboard = keyboard. getstate (); // back or escape exits our game on Xbox 360 and windows if (gamepad. buttons. back = buttonstate. pressed | keyboard. iskeydown (keys. escape) This. exit (); // move 400 pixels each second float movefactorpersecond = 400 * (float) gametime. elapsedrealtime. totalmilliseconds/1000.0f; // move up and down if we press the cursor or gamepad keys. if (gamepad. DPAD. up = buttonstate. pressed | keyboard. iskeydown (keys. up) scrollposition + = movefactorpersecond; If (gamepad. DPAD. down = buttonstate. pressed | keyboard. iskeydown (keys. down) scrollposition-= movefactorpersecond; base. update (gametime);} // Update (gametime)

The previous lines of code are the same as the previous example. Next, we need to calculate the number of pixels to move each frame. If we draw only one frame in one second, the value of the variable movefactorpersecond is 400. If we draw 60 frames in one second, it takes 1/60 seconds to move one frame, at this time, the value of this variable is 400/60 (where gametime. elapsedrealtime indicates the interval between two adjacent frames ).

The value of the scrollposition variable changes every time you press the up or down key. In this case, the value of scrollposition is added to the Y coordinate in the draw method, and the background can be moved up and down, the Code is as follows:

 
Protected override void draw (gametime) {graphics. graphicsdevice. clear (color. green); sprites. begin (); int resolutionwidth = graphics. graphicsdevice. viewport. width; int resolutionheight = graphics. graphicsdevice. viewport. height; For (INT x = 0; x <= resolutionwidth/backgroundtexture. width; X ++) for (INT y =-1; y <= resolutionheight/backgroundtexture. height; y ++) {vector2 position = new vector2 (x * backgroundtexture. width, y * backgroundtexture. height + (INT) scrollposition) % backgroundtexture. height); sprites. draw (backgroundtexture, position, color. white);} // For sprites. end (); base. draw (gametime);} // draw (gametime)

now your game can be moved up and down, which is cool for your first small application?

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.