Xna 4.0 game development by example code


















The conversation digs into the application in question, a Windows Phone app for allowing tech support personnel manage tech support problems on the go. Then David discus. Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think! We've got automatic conversion tools to convert C to VB.

NET , VB. NET to C. Also you can compress javascript and compress css and generate sql connection strings. Developer Fusion - The global developer community for. NET and Java programmers.

Home Mobile Windows Phone Books. XNA 4. A step-by-step tutorial to using Microsoft XNA by creating four different styles of video games. What you will learn from this book Install the Microsoft XNA Framework and its required tools Build XNA Game projects and associated XNA Content projects Create a puzzle-style game exploring the concepts of game states, recursion, and 2D animation Add sound effects to your game with a "fire-and-forget" sound effects manager Create a particle system to generate random explosions Implement sound effects, collisions, and particle-based explosions by building a space shooter inside a chaotic asteroid field.

If any of them are pressed, we modify the value of moveDir by adding the appropriate vector component to its current value. After all the four keys have been checked, we will check to see if the value is still Vector2. If it is, we will skip updating the moveDirection variable.

If there is a non-zero value in moveDir , however, we will use the Normalize method of the Vector2 class to divide the vector by its length, resulting in a vector pointing in the same direction with a length of one unit. We store this updated direction in the moveDirection variable, which is maintained between frames. When we have accounted for all of the possible inputs, we update the player's position by multiplying the moveDirection by playerSpeed and the amount of time that has elapsed since Update was last called.

The result of this multiplication is added to the playerPosition vector, resulting in the new position for the player. Before we can assume that the new position is ok, we need to make sure that the player stays on the screen. We do this by using MathHelper. Clamp on both the X and Y components of the playerPosition vector. Clamp allows us to specify a desired value and a range. If the value is outside the range, it will be changed to the upper or lower limit of the range, depending on which side of the range it is on.

By limiting the range between zero and the size of the screen minus the size of the player , we can ensure that the player's sprite never leaves the screen. We will use this method to determine when the player collides with a letter and how to respond to that collision increase or decrease the player's score, advance the spelling of the current word, and so on. The last of the predefined methods in the XNA game template is Draw.

This method is called once after each call to Update and is responsible for the game state for the current frame. By default, all that the Draw method does is clears the display and sets it to the CornflowerBlue color.

To draw the visual components of our Speller game , perform the following steps:. Alter the GraphicsDevice. Clear Color. CornflowerBlue call and replace Color. CornflowerBlue with Color. Black to set the background color. When using the SpriteBatch class, any calls to draw graphics or text must be wrapped in calls to Begin and End. Begin prepares the rendering system for drawing 2D graphics and sets up a specialized render state. This is necessary because all 2D graphics in XNA are actually drawn in 3D, with the projection and orientation configurations in the render state to display the 2D images properly.

In our case, the only graphical image we are drawing is the square that represents the player. We draw this with a simple call to SpriteBatch. Draw , which requires the texture we will use, the location where the texture will be drawn on the screen relative to the upper-left corner of the display area , and a tint color. Because our square image is white, we could set any color we wish here and the player's square would take on that color when displayed. We will use that to our advantage in just a moment when we draw the text of the word the player is trying to spell.

After the player has been drawn, we loop through each of the letters in the letters list and use the SpriteBatch. DrawString method to draw the letter at its position, using the letterFont we created earlier. Normally, we will draw the letters in white, but if the player runs into this letter and it is not the letter they are supposed to hit we will draw it in red.

Next, we need to display the word that the player is attempting to spell. We display the text Spell: near the bottom center of the display, using the bounds of the current window to determine the location to draw.

In order to colorize the word properly, we need to split the word into different parts as what the player has already spelled, the current letter they are targeting, and the letters after the current letter.

We do this using the Substring method of the string class, and then draw these three components with different color tints. We utilize the MeasureString method of letterFont to determine how much space each of these components occupies on the screen so that we can position the subsequent strings properly.

We will actually break these down into other helper functions as well. To implement the CheckForNewWord and its helper methods, we will perform the following steps:. In step 1, we generate a random number using the Next method of the Random class.

Given an integer value, Next will return an integer between zero and that number minus one, meaning we will have a return value from zero to fourteen. Using a select statement, we return the randomly determined word.

Note that we should never hit the last return statement in the function, so if we are ever asked to spell the word BUG , we know something is wrong. The FillLetters method is used to populate the letters list with letters and their locations on the screen. We could simply generate random locations for each letter, but then this would leave us with the potential for letters overlapping each other, requiring a check as each letter is generated to ensure this does not happen. Instead, we will generate a list of potential letter positions by building the locations list.

This list will contain each of the possible places on the screen where we will put a letter by spacing through a grid and adding entries every 25 pixels in the x and y directions. The exception is that we define an area in the center of the screen where the player will start and we will not place letters.

This allows the player to start each round without being in contact with any of the game letters. Once we have our list of locations, we clear the letters list and generate 20 letters.

We start with the letters required to spell the target word, pulling letters from the currentWord string until we reach the end. After that, the letters will come from the alphabet string randomly. Each letter is assigned one of the locations from the locations list, and that location is then removed from the list so we will not have two letters on top of each other.

If it is, the player's position is reset to the center of the screen and a new word is generated using PickAWord. To complete the Speller project we need to add the CheckCollosions method by performing the following steps:.

Execute the Speller project and play! The following screenshot shows how our game will look when we execute it:. CheckCollisions loops backward through the letters list, looking for letters that the player has collided with. Going backwards is necessary because we will potentially be removing items from the list, which cannot be done in a foreach loop. If we were moving forward through the list, we would disrupt our loop by deleting the current item, which would cause it to skip over the next items in the list.

Moving backwards through the list allows us to remove items without adjusting our loop's logic. In order to determine if we have collided with a letter, we build two rectangles. The first rectangle represents the position and size of the letter we are checking against, by using the letter's Position value and the size of the letter calculated with MeasureString. The second rectangle represents the area occupied by the player's sprite.

The Intersects method of the Rectangle class will return true if these two rectangles overlap at any point. If they do, we know we have hit a letter and need to take action. If the letter impacted is the next letter in the word that the player is spelling, we increment the player's score and remove the letter from the list.

If the letter is not the player's current target, we check the letter's WasHit value. If it is false, we have not run into this letter, so we reduce the player's score and mark WasHit to true. If WasHit is already true, we simply do nothing so as not to deduct from the player's score multiple times while the player passes over an incorrect letter. When the rectangles do not intersect, we know we are not currently in contact with this letter, so we set its WasHit variable to false. This has the effect that once we leave an incorrect letter, it becomes re-enabled for future collisions and point deductions.

Speller is a pretty simple game, but could be enhanced to make a more full-fledged game, by including the following, depending on your level of experience with 2D XNA development:. Beginner: Raise the difficulty by increasing the speed of the player's square as they complete each word.

Intermediate: Record the words with a microphone and play those recordings when a new word is generated. Instead of displaying the entire word during the update method, display only the letters that have been spelled so far. This would turn the game into more of an educational kid's game with the player having to spell out the words they hear.

As a quick-fire introduction to a number of essential XNA topics, Speller covers quite a bit of ground. We have a functional game that accepts player input, draws graphics and text to the screen, generates a random playfield of letters, and detects player collision with them. As we will see, many of these concepts translate into a 3D environment with very little need for modification, other than the need to keep track of positions and movement with an extra dimension attached. We will utilize the Vector3 objects instead of the Vector2 objects, and we will still rely on a 2D plane for much of the layout of our game world.

Additionally, although much of the work in the following chapters will take place with 3D drawing commands and constructs, we will still be returning to the 2D SpriteBatch and SpriteFont classes to construct interface elements and convey textual information to the player. He has built games for everything from the Commodore 64 to the Xbox He is the owner of xnaresources. About this book Move beyond the world of flat 2D-based game development and discover how to create your own exciting 3D games with Microsoft XNA 4.

Publication date: September Publisher Packt. Pages ISBN Chapter 1. Introduction to XNA. System requirements. Graphics Card Shader Model 1. Close Visual Studio Express. What just happened? Speller — Our first XNA game. Flood Control : An explosion in one of the research laboratories has cracked the pressure dome protecting your underwater habitat. Work quickly to construct a series of pipes to pump water out of the habitat, before it floods.

Flood Control is a board-based puzzle game with simple game mechanics and slowly increasing difficulty. Asteroid Belt Assault : After being separated from your attack fleet in hyperspace, you find yourself lost in an asteroid field without communications or navigation systems. Work your way through the chaos of the asteroid belt while combating alien pilots intent upon your destruction. A vertically-scrolling space shooter, Asteroid Belt Assault introduces scrolling backgrounds, along with player and computer-controlled characters.

Robot Rampage : In the secret depths of a government defense facility, a rogue computer has taken control of robotic factories across the world, constructing an army of mechanical soldiers. Your mission—infiltrate these factories and shut down their network links to break the computer's control. A multi-axis shooter utilizing both of the analog control sticks on the Xbox gamepad controller, Robot Rampage generates and manages dozens of on-screen sprites, and introduces world map construction.

Gemstone Hunter : Explore the Australian wilderness, abandoned mines, and ancient caves in a search for fabulous treasures. In Gemstone Hunter, you will construct a classic platform-style game, including a Windows Forms-based level editor and a multi-map "world" to challenge the player. The games are each presented over two chapters.

In the first chapter, the basics are implemented to the point where the game is playable. In the second chapter, features and polish are added to the game. Each game introduces both new concepts and expands on topics covered in the previous games. At the end of each game chapter, you will find a list of exercises challenging you to use your newly-gained knowledge, to enhance previous games in the book.

We will focus on Windows as our platform for the games presented in this book. That said, the code presented in this book requires very little in the way of changes for other XNA platforms, generally only requiring implementation of platform-specific controls gamepads, touch screen, and so on , and consideration of the differences in display sizes and orientation on non-Windows devices. The general requirements are listed in the following table:. Microsoft recommends Shader Model 2. The projects in this book similarly require Shader Model 2.

Development tools include a Windows Phone emulator to test applications, without deployment to a physical device. Xbox Live Silver is free. To get started developing games in XNA, you will need to download and install the software. With the release of XNA 4. Run the setup wizard and allow the installation package to complete.

Open Visual Studio Express. Click on the Help menu and select Register Product. After you have completed the registration process, return to Visual Studio Express and enter the registration number into the registration dialog box. XNA attempts to simplify many of the basic elements of game development by automatically handling things, such as the game update loop and presenting the current frame of graphical information to the display.

To illustrate just how much of the background work is integrated into the XNA project templates, let's jump in straight away and create your first game within a few minutes of finishing the installation. Visual Basic versus C - tutorials and samples on the web. With a five-year headstart on Visual Basic developers, there are a host of XNA tutorials, code samples, and forum posts written for C out on the Internet. In the interest of being able to utilize these resources, I will occasionally point out topics or sections of code and their equivalent in C notation.

In SquareChase , we will generate randomly positioned squares of different colors while the user attempts to catch them with their mouse pointer before they disappear. While building the project, we will discuss each of the major code sections pre-defined by the XNA templates. Under Templates , select Windows Game 4. Name the project SquareChase this will automatically update the Solution Name.

Each of the XNA project templates is a series of files and settings that get copied to your new project folder. Included in this set of files is the Game1. When you create your project, the Location field specifies where it will be saved.

By default, Visual Studio creates a folder in your user documents area called Visual Studio to store both programs and configuration information.

Under this folder is a Projects folder that contains subfolders for each new project you create. Make backups of your projects on a regular basis. You do not want to lose your hard work to a disk failure! The most basic XNA game will have all of its code contained in the file called Game1. This file is generated when you create a new project and contains override declarations for the methods used to manage your game. In addition to the Game1 class' declarations area, there are five primary methods that you will customize for any XNA project.

Right below the class declaration for Game1 is the class level declarations area. By default, this area contains two variables:. The graphics object provides access to, not surprisingly, the system's video card. It can be used to alter the video mode, the size of the current viewport the area that all drawing work will be clipped to if specified , and retrieve information about Shader Models the video card supports.

XNA provides the SpriteBatch class to allow you to very quickly draw 2D images called sprites to the screen. The spriteBatch variable is an instance of this class, which we will use for all of our drawing purposes in SquareChase. The declarations area is the spot for any variables that need to be maintained outside of any of the individual methods discussed next, such as LoadContent , Update , and Draw. In practice, any data that you need to keep track of throughout your game will be referenced in some way in your declarations section.

Here is a quick breakdown:. You will use this to generate random coordinates for the squares that will be drawn to the screen. We will define a small texture in memory to use when drawing the square. SquareChase will generate random squares and store the location in this variable. Their score accumulates in this integer variable.

When the counter reaches zero, the square will be removed and a new square generated. TimePerSquare : This constant is used to set the length of time that a square will be displayed before it "runs away" from the player. The Color structure identifies a color by four components: red, green, blue, and alpha. Each of these components can be specified as a byte from 0 to , representing the intensity of that component in the color.

Alpha represents how transparent the color is, allowing things already drawn behind it to show through. XNA drawing functions utilize pre-multiplied alpha, meaning that the alpha value has already been reflected in the other components of the color. We can accomplish this by simply creating a color with an RGB value and multiplying it by the desired alpha level we wish between 0.

If your experience with Visual Basic is primarily VBScript-related, you may not be used to specifying data types integer, single, Texture2D, and so on to your variables. VBScript uses a generic " Variant " type that is interpreted by the runtime into a type that makes sense for what you are trying to do with it. By contrast, Visual Basic. NET requires that your variables specify a data type that determines how they are allocated in memory and what you can use them for.

In the case of SquareChase, we are using two basic data types:. Integer : It is a whole-number value between -2,,, and 2,,, This is equivalent to the C type " int ". Single : This is a floating-point number. The numeric range for Singles depends on the digits of precision specified. This is equivalent to the C type " float ". The XNA templates define an instance of the Microsoft. Game class with the default name Game1 as the primary component of your new game. Slightly more goes on behind the scenes, as we will see when we add an XNA game to a Windows form in Chapter 8 , Gemstone Hunter: Put on your Platform Shoes , but for now, we can consider the Game1 constructor as the first thing that happens when our XNA game is executed.

The class constructor is identified as Public Sub New , and by default, the constructor contains only two lines:. For most of the games in this book, we will not need to make extensive modifications to the Game1 constructor, as its only job is to establish a link to the GraphicsDeviceManager object , and set the default directory for the Content object, which is used to load images, sound, and other game content.

Many of the items that we define in our code will be classes. A Class is logical grouping of data and code. We can define new classes either from scratch, or based on existing classes. When they are based on other classes, they are said to inherit from a base class.

We create instances of our class in order to use them, called objects. In the previous code snippet, the graphics object is assigned a new instance of the GraphicsDeviceManager class. The code portions of an object are called Methods. In Visual Basic, methods are either Subs or Functions.

A class can have a special Sub called New , which is the class constructor.



0コメント

  • 1000 / 1000