yazik.info Programming Xna Game Studio 4.0 Programming Pdf

XNA GAME STUDIO 4.0 PROGRAMMING PDF

Thursday, August 29, 2019


XNA Game Studio Programming Free Books Download PDF / Free Books Online / Free eBook Download PDF / Free Game Developers Guide to Cybiko . Table of Contents. Storing Games on the Xbox or Windows Phone Running the Same XNA Game on Different Devices XNA Game Studio Programming Developing for Windows® Phone 7 and Xbox ® Developer's Library Series Visit yazik.info for a complete.


Xna Game Studio 4.0 Programming Pdf

Author:RACHELL DESJARLAIS
Language:English, Spanish, Arabic
Country:Serbia
Genre:Politics & Laws
Pages:510
Published (Last):17.04.2015
ISBN:661-2-26826-181-4
ePub File Size:20.44 MB
PDF File Size:18.60 MB
Distribution:Free* [*Register to download]
Downloads:24163
Uploaded by: MAUREEN

of XNA Game Development by Example: Beginner's Guide (C# edition) and . Did you know that Packt offers eBook versions of every book published, with PDF . utilizing the DirectX and Direct3D Application Programming Interfaces ( APIs) . develop games using XNA Game Studio, you will need a computer capable. Now you can build your own games for your Xbox ®, Windows® Phone 7, or Windows-based PC—as you Microsoft XNA Game Studio Learn. Working with Content Using XNA Game Studio. device, from the original gigabyte (GB) device to the latest 4 GB device, can be connected to your PC you .

Although you can check the IsActive property of the game in the Update method, you may want to handle some things outside of the Update. You can override the method to do so in these procedures. The GameComponent class implements a couple of interfaces that allow it to be hooked into the Game class and be given the chance to automatically update itself many times per second. The DrawableGameComponent class inherits from GameComponent and implements an interface that allows it to draw itself in the same way GameComponent gets updated.

The Services property of the Game class is an instance of this class. Suffice it for now to say that Game Services allow parts of a game to communicate with each other in an object-oriented manner.

It tells you how much time both game and real time has passed since the last time the method it is passed to was called and how long the game has been running. Some people have managed to get their game running in controls, such as panels that are placed on a regular form, and in ways not expected, such as creating level editors using the game framework.

The GameWindow object has helped them do this.

Index of /pdf/Gentoomen Library/Computer Graphics/

You can use this class to get at the properties of the GraphicsDevice class to set up multiple viewports to allow split-screen play and retrieve and set the current pixel and vertex shaders, among other tasks. You saw how to get to this property a few pages ago when we talked about the Game class. Alternatively, you can call the ToggleFullScreen method to switch between display modes.

The Preferred… properties allow you to change some default settings for your game. Prior to starting your game you can check the three Valid… properties to ensure, to some extent, that the hardware supports your game. The class exposes a half-dozen events related to changes in the graphics device.

For example, if you wanted to execute code when the device is reset such as when the resolution or color depth is changed , you would do something like the following: Listing public class Game1 : Microsoft. Clear Color. IDrawable The IDrawable interface contains one method, two properties, and two events. The DrawOrder property specifies when the implementer is drawn in the list of other IDrawable objects. The Visible property determines if the Draw method should be called. The Game object will automatically call the Draw method for all components in its GameComponents list that implement this interface.

Collection 10 Chapter 1 The part means only objects that implement the IGameComponent interface can be added to the collection. Invariably any component that implements this interface will also implement the IUpdateable interface, which contains an Update method that the game will call automatically each time through the game loop that runs during the game.

The interface also contains an Enabled property, which allows you to have the Update method not be called, and an UpdateOrder property, which lets you specify the order in which the components in the GameComponents list have their Update method called. The GraphicsDeviceManager that gets added as a member of the Game class instance implements this interface. The whole point of the XNA Framework is to take care of a lot of the startup code that you would normally have to write and make it easier to interact with the hardware.

The GraphicsDeviceManager is one of the classes that does this. Pipeline Assembly The Pipeline namespace provides the functionality for creating and using your own content pipeline. The other four DLLs are importers for the different kinds of content that you can use out of the box — shaders, FBX and X model files, and textures which can be one of a half-dozen different formats. The Microsoft. Framework namespace contains classes and enums related to math and geometry functionality.

Audio namespaces in Chapter 5 when we add sound and music capability to our game.

An instance of this class is automatically created for you in the Game class if you use one of the game templates that comes with Game Studio.

Design namespace contains a dozen classes for converting objects and data types to other objects and data types. GamerServices namespace is new in Game Studio 2. The Gamer class contains Gamertag and a custom Tag object for the gamer. You can also get a list of Gamer objects for all the players on the local system using SignedInGamers. XNA Framework and Game Studio 13 Profile information is contained in a GamerProfile object: Figure This allows you to display information about the player in your game, which gives other players an idea of the type of gamer he or she is without having to look it up by gamertag.

The SignedInGame class is a bit different from the regular Game class. Its members deal mainly with online-related data: Figure GameDefaults is a set of data that can be used for almost every game, although some are specific to certain types of games, such as first-person shooters or racing games.

The Guide class allows you to, not surprisingly, access the Guide user interface and other functionality. You can also do things like show the sign-in interface, messages, friends, gamer cards, and more. By far the biggest in the assembly, the Microsoft. Graphics namespace will quickly become your friend as you explore the world of XNA game development. The namespace contains over objects ranging from 2D and 3D to classes that allow you to work with effects to structures that allow you to investigate the capabilities of the graphics device on a machine.

Probably the second most important part of the assembly, the Microsoft. Input namespace is just what you think it is — a collection of classes and enums for working with input devices. A generic GamePad class and the typical Mouse and Keyboard classes are housed here.

The big change in Game Studio for the typical. NET developer is that these devices are not used in an event-driven fashion. Since games are constructed differently from normal business apps, the method of dealing with input devices 16 Chapter 1 changes. You check the state of the device to see what controls on it are being used and handle things accordingly. It is possible to construct one or more classes to implement an event-driven system, however. Storage class gives you access to the devices on which to read and write data on both the PC and Xbox These can be hard drives, memory units, or USB devices such as thumb drives and portable hard drives.

While you can use the System. The newest addition to the Framework, the Microsoft. Fortunately, the XNA Team has made it less difficult to do this than if you were using even regular. NET functionality. The first beta, released in August , did not include some of the features now available such as the content pipeline and functionality for easily creating 3D games and for developing Xbox projects. It did include a starter kit for creating a Spacewar game.

There were some great 2D games developed using this beta version. Following another beta version, the 1. Almost immediately more great games started popping up. A lot of additional content has already been released for use with Game Studio — sample games, starter kits discussed later in this chapter , and tutorials. GarageGames has also released the first version of their Torque X software, which integrates with Game Studio, and other companies are preparing software for use with Game Studio.

Previously you had to distribute your code as well as your assets in order for others to be able to run your game. Version 2. In addition to a lot of fixes and improvements, it added one of the most desired pieces of functionality — the ability to create networked games that can be played over the Internet via the Live system on both the Xbox and Windows PCs. In the week following its release, many of the samples and other content were updated for the new version, and much more has probably been released in the time between the writing of this book and you reading it.

Among the Game Studio features are the templates and starter kits for getting a game up and running with virtually no code needed by the developer, the Game Component and Sprite Font templates, and the built-in content pipeline. All of these features combine to make Game Studio an extremely powerful game development environment. These are the only supported operating systems.

Steps for doing this and setting up your PC and Xbox will be covered along with Xbox development in Chapter It creates a very basic skeleton for you. The program. Generic; Microsoft. Framework; Microsoft. Audio; Microsoft. Content; Microsoft.

GamerServices; Microsoft. Graphics; Microsoft. Input; Microsoft. Net; Microsoft. GetState PlayerIndex. Pressed this. The constructor is called when the instance of the class is created. The Initialize method is called after the object is created. The LoadContent method is also called when the object is created, after the Initialize method. The UnloadContent method is called when your game ends and allows you to clean up after yourself. After the game is initialized and starts running, the Update and Draw methods are repeatedly called.

Depending on whether or not the game is set to run at the refresh rate of your monitor which defaults to true , the two methods will get called either at the refresh rate for example, a refresh rate of 75 Hz will cause the methods to be called 75 times per second, or approximately every milliseconds or as quickly as possible. The SynchronizeWithVerticalRetrace property of the graphics device specifies which timing is used.

You should usually be fine with leaving the property set to true. If you find yourself writing the same code over and over to do things that most games will require, it might be wise to package it up in a library instead of copying files from project to project.

Code reuse is something that you would do well to practice. Multiply this time by the number of games you create and it starts to add up. Time is money, after all. Xbox Game The Xbox Game template is virtually identical to the Windows Game template, but targeted at the Each starter kit contains a working version of a specific type of game.

This game can be expanded upon or changed as needed to allow you to quickly create your game without having to write a lot of code. Developed by Andy Dunn of ZBuffer Games, this starter kit gives you a ready-to-run two-player game complete with multiple weapons and ships.

Figure Marblets The Marblets starter kit is similar to the Bejeweled type games that became popular back around PopCap Games is one of the most well-known developers of these types of games. It comes with three different tracks for three levels of difficulty. It would be well worth the cost of upgrading to be able to dig into the code for this game and tweak it to change the way the game works. Developed by Fabio Policarpo, the game is very reminiscent of the old Descent games which I personally loved.

Players fly around in a series of tunnels and rooms where there is really no up or down. The kit makes full use of the advanced effects available in Game Studio. While the multiplayer component is only split-screen at the moment, I expect someone to soon modify it to support LAN or Internet play. Say you want to display a splash screen when your game starts.

That one line of code is pretty deceiving. Each type of file has its own importer, but similar types of content are grouped together for the processor, as you can see when you look at the Content Importer and Content Processor properties of a piece of content that you include in Figure a project, as shown in Figure Note that some types of content have more than one option for processing, such as a texture.

One of the nice things about the content pipeline is that you can use a meaningful name to load the assets instead of a possibly arbitrary file name.

To load a different type of asset, say an audio file, you just change the type in the Load method and the name of the piece of content.

The recently released game BioShock, for instance, had a person dedicated just to making the water look and act realistic. Games today are such huge projects and technology advances so rapidly that it would be difficult for someone to keep abreast of the latest changes in every area. Even if you spent all your time studying and working with all the various game technologies out there, it would be difficult, if not impossible, to gain and maintain the knowledge necessary to use them to their full capabilities.

If you decide on 2D, you still have some choices to make, such as: n What kind of view you should use — top-down, side-scrolling, isometric, etc. Do you create 3D models for the sprites and render views of them out to 2D image files and use 2D backgrounds? Do you use some other method? Again, the type of game might influence this and could even make it a non-issue.

If so, do you create images with all the different colors or do you do the coloring with code? It is also about decreasing the quality of textures for these objects, a process known as mipmapping. By not doing so, you gain some performance benefit. This will probably be somewhat dictated by whoever is doing your modeling. That means a kind of balancing act in giving the player the option of using the available devices 32 Chapter 2 on a specific platform as well as ensuring all the devices available for each platform work the best for that platform.

If your game is more than just a point and click, you should consider giving the player the option of changing the control configuration and saving it.

What you think might be the best configuration might not suit everyone. Your game will be much better received if you give the player the option of setting up the controls to their liking. For Xbox games some of the burden is handled for you. You start with the existing Live infrastructure and build on top of it. NET Framework. Many games are set up to communicate with a central server that stores information about games that are currently being played and games where players are looking to create or join a game.

The game will display an interface to provide you with the information you need to find a game.

XNA Game Studio Programming

This information will probably include things like the ping to the server regardless of whether that server is a player acting as the host or a dedicated server , the number of players currently in the game and the maximum number of players for that server, the type of game deathmatch, capture the flag, etc.

Your game will be much better received if you give the player the option of setting up the controls to their liking. For Xbox games some of the burden is handled for you. You start with the existing Live infrastructure and build on top of it. NET Framework. Many games are set up to communicate with a central server that stores information about games that are currently being played and games where players are looking to create or join a game.

The game will display an interface to provide you with the information you need to find a game. This information will probably include things like the ping to the server regardless of whether that server is a player acting as the host or a dedicated server , the number of players currently in the game and the maximum number of players for that server, the type of game deathmatch, capture the flag, etc.

Game Development Overview 33 n Do you want to allow the player to just jump into a game without having to pick from a list? Some games have taken to providing this feature, including the well-known Halo. In some cases, it might be necessary to end the game; in others, one of the other players could become the host.

Will that information be able to fit inside a standard packet? This may be dependent on the type of game. Connectionless service; no session is established between hosts. TCP guarantees delivery through the use of acknowledgments and sequenced delivery of data. UDP does not guarantee or acknowledge delivery, or sequence data. Programs that use TCP are provided assurance of reliable data transport. Programs that use UDP are responsible for providing any reliability needed to transport data.

TCP is slower, has higher overhead requirements, and only supports point-to-point communication. UDP is fast, has low overhead requirements, and can support point-to-point and point-tomultipoint communication.

Shooters and faster paced games usually go with UDP since the speed is more important than the guarantee of delivery. If a packet is lost, the game will just compensate the next time it receives one.

While this can cause problems, these can be overcome by having the game manually require the delivery of some packets say one where a player is killed. The complexity depends on several factors — the type of game, the knowledge of the person doing the AI programming, and the time you have to create the system. Good AI in some types of games RTS games, for example is extraordinarily difficult to do without cheating.

And they will figure it out, have no doubt. Players these days will pull your game apart piece by piece to see what makes it tick and how they can beat it. There have been several books written on AI game programming. If your game is going to feature both human opponents and AI and you have to choose which one to do first, I would suggest working on the code to allow human opponents to play before trying to implement AI opponents.

Human intelligence is going to be more challenging for a player than AI, making the game more fun for most types of players. The AI will literally have a one-track mind — head toward the player and try to kill him.

Try playing an FPS without the crosshair for aiming. How would you change game options or load and save games without dialogs? Menus and things like lists and options can be created using plain text, as well as displaying information to the player like the number of rounds of ammo left in the weapon, the stats of the character, score, time remaining, etc.

Drop something in that works and use it until you have to replace it. Physics System Physics systems are becoming more popular with the big games. From racing games like Project Gotham where the cars operate like you expect them; to shooters like Crysis where bullets can destroy objects and explosives have a blast radius and affect the terrain; to even RPGs like Oblivion where the world feels alive partly because 36 Chapter 2 of the way you can interact with it, the ability for the game world to operate and feel like the real world is currently the big thing besides graphics.

Now think of it without any sound or music. Imagine Halo without either one. Imagine if a character were firing a rocket launcher and the sound that was triggered was that of a bubble popping.

Half-Life 2 is a good example. Graphics files, both 2D and 3D; music and sound effects files; information about objects in your game and how they behave physics behavior, AI behavior patterns, etc. How do you do this though?

You need a way to know when to load specific data and what needs to be rendered to the screen every frame. This is where the idea of game states comes in. A card game could have states such as dealing the cards, betting, playing cards, and resolving the winner of the hand. PlayingGame; else if mnuOptions. Options; else if mnuQuit. Exit ; if GamePad. Exit ; break; case GameState.

The player can be looking at the main menu, looking at the options screen, or playing the game. Initially the variable holding the value of the current state is set in the constructor to the main menu. Looking down at the Update method we see how the different states are handled.

If he has, we set the variable holding the current game state as appropriate so that when the Draw method is called the proper thing will be drawn. If the options menu is being displayed, we check to see if the menu item for going back to the main menu has been selected or the Back key was pressed and, if so, we set the state back to the value for the main menu.

What happens in any other case in the options screen depends on what it allows. If the player is playing the game, a lot of things could be happening. From the options given it looks like this might be an RPG talking to people, downloading stuff, etc. There would obviously be a lot to this section, much of it probably wrapped up in classes.

Game Development Overview 41 The same kind of thing happens in the Draw method. We know what has to be rendered based on the variable holding the current game state. This allows you to easily expand the game if you want to implement new features.

Want to add the ability to save your game? Add a save game screen and have the manager display it when necessary. The same would go for options, dialogs, things like inventory screens, HUDs, etc. Even within the screens we could have substates that we use if the game is fairly complex. All of this happens within what is called the game loop, like so: XNA makes it a bit easier for budding game developers.

All the normal initialization code is done in the Framework so you never need to worry about it although you can change some of the things that are set by default — 42 Chapter 2 backbuffer size, for example.

It also sets up the loop for you, hiding it in the guts of the Framework. The input, update, and render procedures all get called automatically; you just fill in the update and render methods.

We saw the typical skeleton for an XNA game in the previous chapter that gets created in the program. It would get much too disorganized very quickly. The object-oriented nature of the Framework should make it much easier to organize your code into self-contained objects that you can reuse in all your games.

The frame rate is basically how many times per second your game loop runs, assuming you draw to the screen every frame. You can also look at it as how many times per second you redraw the screen.

Anything from 30 to 40 or more frames per second will produce a smoothly running game. The Update method is called automatically for us every time through the loop. We simply add that time to a variable until the value of that variable is equal to or greater than Pretty easy, huh? This class can be dropped into any existing XNA Game Studio project and hooked in to the Components collection of the game. All you have to do is tell it where to draw the information.

By implementing an interface, the class agrees to provide the functionality for the abstract methods in the 44 Chapter 2 interface. You have to do this in order for the XNA Framework to be able to interact with the component, such as automatically calling the Update and Draw methods. Update should be called; false otherwise. Lower values are updated first.

Enabled property changes. EnabledChanged; the IUpdateable. UpdateOrder property changes. IUpdateable brings the Update method and some associated members to the component. The XNA Framework provides one other interface that your components can implement, the IDrawable interface, which allows the component to draw itself to the screen. Objects with a lower value are drawn first. Draw should be called in Game. Draw should be called; false otherwise.

DrawOrder property changes. DrawOrderChanged; the IDrawable. Visible property changes. Game Services Game services are a mechanism that allows objects to interact with each other without requiring the holding of a reference. A service is basically just an interface that allows code to query it and get to the members or events of the object that implements the interface.

To use a service along with a game component, you first need to create the service. IndexOf room ]. A game level is made up of a list of LevelRoom objects: For our purposes, this is a simple class with a Name string member.

The room has one or more exits, which is a list of Direction enum values: In our Game object we create an instance of the component, add it to our GameComponents list, create an instance of the service, and add it to the Services list while tying it to the component: Load ; this.

Add gameLevel ; this. Listing public class Entity: AddRange gls. We then use that service to access the properties and methods of the GameLevel object that has been exposed to the service.

A visual representation of the relationships between components and services might make things a bit easier to understand. Figure Hopefully this brief look at game components and services has given you a little bit of an understanding of how they work and the power that they contain. Figure 52 Chapter 2 The GameScreen class is the base class for all the other screens.

The inclusion of the transition effect to fade the screens in and out is a very nice feature that will help the game look a little more professional than if they were to just pop in and out. Note the two methods of making a screen go away.

The ExitScreen method will make the screen transition out normally. During a game you might not want screens to fade in and out. The RemoveScreen method gives you the ability to do this. The LoadingScreen is only displayed right before the GameplayScreen. If your game loads quickly enough you could easily remove this screen.

AddScreen new OptionsMenuScreen ; break; case 2: If you have no need for a loading screen you could replace the line with the following: GetScreens screen. ExitScreen ; ScreenManager. If you need to do any heavy-duty work before you start the game, such as loading world data, you will want to leave this loading screen in place. The BackgroundScreen is just what it says, a screen that is always present no matter what other screens might be displayed.

Those are the screens that inherit from GameScreen. The rest inherit from MenuScreen which itself inherits from GameScreen , which offers some additional functionality: Listing abstract class MenuScreen: FromSeconds 0. TransitionOn position.

R, color. G, color. DrawString ScreenManager. Font, menuEntries[i], position, color, 0, origin, scale, SpriteEffects. None, 0 ; position. The current item is drawn in yellow and will pulse, changing size. What happens when you select that item is up to you. Usually you would take the player to another screen, but you can override the way the class works and do whatever you want. Listing class OptionsMenuScreen: Add string.

Empty ; MenuEntries. Length; break; 58 Chapter 2 case 2: The first item loops through the items in an enum, the second loops through a string array, the third toggles a Boolean variable between true and false, and the fourth increments an integer variable. In order to transition between all these screens, a ScreenManager class is used. AddScreen new BackgroundScreen ; screenManager. From there, screens are added to and removed from the list as you navigate the screens.

There are only a handful of properties: In this case, trying to loop through a list where one item has been removed would cause an error. You can see this happen in the Update method of the class: Clear ; foreach GameScreen screen in screens screensToUpdate. Count - 1]; screensToUpdate. RemoveAt screensToUpdate. TransitionOn screen.

It does this by keeping two variables for the state of the keyboard and gamepad: Escape CurrentGamePadState. Released CurrentGamePadState. Depending on your comfort level, you could even try tweaking the sample to change how some things work. For example, you could try displaying the menu items one by one, or having them come in from the bottom of the screen or alternate coming in from the left and right.

The code is pretty flexible so you can do some things to make your game uniquely your own. There are a couple of good reasons for this. Creating a game with a known rule set and gameplay will be much easier than trying to come up with your own idea for a game and implementing it on top of learning the ins and outs of game programming. The less you have to deal with for your first projects, the better.

Why should you have to put any thought into creating rules and coming up with gameplay elements for a learning project? It would be a much better use of your time to simply write a clone of an existing game. The second reason is that most people find 2D game programming easier to learn than 3D. That third dimension adds a lot of complexity to a game that most programmers just getting into game development would find a significant obstacle to overcome quickly and easily.

This class simply describes a 2D array of texels using code. Texel is short for texture element. Depending on how the object that the texture is mapped onto is rendered there may be one or more pixels per texel or one or more texels per pixel. The XNA Framework hides most of the gory details, taking care of the little things to let you concentrate more on the big things. Give it a name and click OK. Draw a star on it, so that it looks something like this: Figure Save it as a.

Find the file for the image you just created and click OK to add it to the project. Figure XNA Game Studio automatically recognizes the file when you add it as one that it knows how to handle using the content pipeline.

Open the Game1. Load "star" ; Here we see how we use the Asset Name property of the image. We pass it as a parameter to the Load method of the ContentManager object that was created for us when we started the project. This leads us to the next piece of the 2D puzzle, the SpriteBatch object.

It has two members for drawing content to the screen, both of which are overloaded. The other method, DrawString, does just what it says, renders text to the screen.

The Begin method takes a parameter that allows you to specify some effects that will be applied to everything you draw until you call the End method. The basic Draw method has six overloads that allow you to do things like draw only part of a texture, scale it, rotate it, apply effects, and sort by depth yes, even in 2D you still have a form of 3D. Begin ; spriteBatch.

[PDF] XNA Game Studio Express: Developing Games for Windows and the Xbox [Download] Full

White ; spriteBatch. End ; Simple, huh? The idea was to draw just the star, not the background as well. What happened? Comment out the Draw method line and replace it with: Figure What we really need is a way to have SpriteBatch draw the background of the image transparently. We can modify the image file to take advantage of the built-in background masking that SpriteBatch has. To do this we need to use Magenta as the background of the image.

Save it as a new image, newstar. Perhaps if we spin it around in place… Rotation Rotating a sprite is just a little more complicated than drawing one normally. There are 0. It might be good to create a constant for this: How will this get updated? It looks like the Update method might do the trick.

The XNA Framework calls this as quickly as it can so we can use this to update our angle. White, rot, origin, SpriteEffects. None, 0. The other variable we create is the point around which the rotation will take place. This is a center pixel in our image.

Later on you can try changing this value to see what effect it has on the rotation. Set the two values to 0, for instance. Our call to the Draw method has changed a bit. The third parameter of null is the source rectangle. Passing null means we want to draw the entire texture. The fifth and sixth parameters are the variables we set earlier.

The next is an enum that specifies what effects we want to apply to the drawn image. The last parameter is used to specify at what depth we want the image drawn. This allows us to have semi-3D rendering. Feel free to set the parameters to different values and note what happens. This can be used for all kinds of things in games — magical effects, animation, protective shields for sci-fi type games; the list is as large as your imagination.

Add these two variables: Comment out the existing line and replace it with the following: You can flip either vertically or horizontally by setting one of the SpriteEffects enum values: None SpriteEffects. FlipHorizontally SpriteEffects. You can also start from scratch. Create a new Windows Game project and modify the image from the previous sample like so: Black ; spriteBatch. FlipHorizontally, 0. FlipVertically, 0.

End ; base. We draw the image normally first, flipped horizontally next, and flipped vertically last. As with the rotating sample, you can change the values for the origin to modify where the flipping originates. In that case you need to use a technique called masking to make a portion of a sprite transparent.

What we do is create a texture where the alpha channel is set up in such a way that it makes our hole: Figure 2D Graphics 75 The texture on the right is set so that the black pixels will be transparent and the white will not.

Figure Since Game Studio supports this texture format, we can simply add the file to our project and load it as we normally do. We can then draw the texture with or without alpha blending to hide or show the information: CornflowerBlue ; spriteBatch. None ; spriteBatch. Pressed Keyboard. IsKeyDown Keys. You can either make the changes to the rotating sample or start a new project and copy the code from that sample. Initialize them in the constructor: Next 0, graphics.

We just change the first two parameters to generate the random location. The GetRandomColor function generates a random value for the red, green, blue, and alpha components of our color.

The alpha component of the color specifies the transparency of the color. The alpha component of the color controls this. The lower the number, the more you can see through it. This value and the color behind the sprite are blended together by default in the call to our Draw method. Copy the newstar. Figure If we were to use the newstar texture, the color blending would start with a blue base color and produce a far different result. Change the color to blue or any other color and note the effects when you run it.

There are a lot of possibilities with coloring, many of which mean fewer graphics that will have to ship with your game. Tiling Many 2D games use tiling to draw the game world since usually the world is much too large to have one image represent it. Think about how big a Mario game world image would be, for example.

You just create a set of data that describes the world. In its simplest form, this could be an array that tells what tile is to be drawn in each area of the map.

Start a new Windows Game project. Before we do anything else though, we need some tiles. Figure Add the image to your project and call it tiles. We also do a check to see if the tile size will divide evenly into the screen height and width. The LoadGraphicsContent method is where we have to do this: Whoever played a game where the world was this small?

It will no longer be based on the size of the screen so we can just set it to whatever size we want in the constructor: We do this using two integers: Notice that there have been some changes to the Update and Draw methods. Here is the new Update method: One ; if ks. Left gps. Right gps. Down gps.

We get the state of the device and check to see if the arrow keys, or directional pad directions, are pressed.

A Climate for Change

The drawing code has changed only slightly: We have to take into account the starting tile values. We simply subtract the loop counter and starting tile values to figure out where to draw to the screen. It might not really affect performance in this small sample, but it is always a good practice to follow.

Once you understand the basics of tiling, you can create Mariotype platform games, RPGs, scrolling shooters like the arcade games Xevious and R-Type, and whatever other games your imagination can come up with. The idea is still the same, however.

Animating Sprites Animated sprites can be used with tiling and almost inevitably are. Imagine a Mario game where he moved stiff-legged across the screen.

Start up a new Windows Game project. Notice that the second and fourth parts of the image show his feet moving, first the right foot, then the left. If we 2D Graphics 85 were to draw each frame of the animation every time the Draw method was called, it would look like the character was running at super-speed. So we need to slow him down a bit. If we have, we simply reset it to the first frame, 0. End ; Go ahead and compile and run the sample. You should see the character appearing to walk in place in the middle of the screen.

Multiple Batch Rendering While it will probably be rare, there may come a time when you will want to have multiple SpriteBatch objects for your rendering. This will usually be because you run into problems with depth sorting and performance. Besides the non-parameter version, Begin has three overloads: SpriteSortMode is an enum that can be one of five different values.

The following table shows the SpriteSortMode values and how they work. This procedure is recommended when drawing transparent sprites of varying depths. Deferred Sprites are not drawn until End is called. End will apply graphics device settings and draw all the sprites in one batch, in the same order calls to Draw were received.

This mode allows Draw calls to two or more instances of SpriteBatch without introducing conflicting graphics device settings. SpriteBatch defaults to Deferred mode. FrontToBack Same as Deferred mode, except sprites are sorted by depth in front-to-back order prior to drawing.

This procedure is recommended when drawing opaque sprites of varying depths. Immediate Begin will apply new graphics device settings, and sprites will be drawn within each Draw call. In Immediate mode there can only be one active SpriteBatch instance without introducing conflicting device settings. Immediate mode is faster than Deferred mode.

Texture Same as Deferred mode, except sprites are sorted by texture prior to drawing. This can improve performance when drawing non-overlapping sprites of uniform depth. If you want to do both tile rendering and point sprites, using two 88 Chapter 3 SpriteBatch instances might make sense.

Click on the Sprite Font template and name it title. The three properties we decided upon should be very easy to find — FontName, Size, and Style. Go ahead and change the three items. Leave the Spacing element at 2 for now. You may have noticed the CharacterRegions element at the bottom. Go ahead and add the code to declare: And finally we draw some text: Well, luckily the DrawString method has some overloads, just like the Draw method: Just like regular sprites, we can rotate and scale text.

Copy and paste the title. Then create a new SpriteFont object and load it. Last, add some code to draw two more strings, one rotating and one scaling. We can reuse some of the code from our previous sample: White, rot, new Vector2 0,0 , 1. White, 0. There has to be some way to do that, right? Of course there is. The SpriteFont object is a class and, as such, has some functionality to help you use it.

One of the methods of the 2D Graphics 91 class is MeasureString, which is exactly what we need. We can change the code in the Draw method as follows: White, rot, new Vector2 rotating. End ; In a full game, you would probably have a lot of different text that you would store in a resource file of some kind and read it into variables and then use the variables in the MeasureString and Draw methods. For these quick samples though, any other method is not worth the effort and would just distract from the subject at hand.

There are a lot of other effects that you can apply to your text — shadows, glowing borders, materials, etc. We could probably do an entire chapter on text in fact. However, there are already a lot of resources on the web in this area. Check the appendix for links to some of these resources. This is done using viewports. You define an area of the screen as the current area to do your rendering and everything is rendered as if that area is the full screen.

Say you want to make a four-player split-screen game. You could do something like this: Load "white" ; content. We can draw the sprites for each area with the same call to the DrawSprite procedure, but we have to use the area Rectangle as an offset.

The results of the technique are okay, but only because we drew everything in the correct order: A better way might be something like this: We set the background colors in the constructor: White; Color.

Black; Color. Red; Color. Viewport; viewport. Our drawing code then becomes an easy loop: We also get our clipping for free, so any drawing we do outside of the viewport is ignored. The only downside to this technique is beginning and ending the SpriteBatch for each viewport. If our drawing were a lot more complicated, it would be even easier than if we were to try to figure out the drawing for each area.

Everything would have to be offset using the Rectangle for each area, which would get messy after a while. Go ahead and open the project. Follow these steps: First off, delete the BackgroundScreen. The easiest way to get rid of the references to it is to 2D Graphics 97 compile and delete the lines that cause errors. Open the GameplayScreen. Delete the Thread. Sleep line in the LoadGraphicsContent method.

Delete all the code in the if IsActive section in the Update method. Delete all the code in the else section in the HandleInput method. Delete the four lines that use the SpriteBatch in the Draw method. At this point you should be able to compile and run the project. If you want to make it larger you can, but you may have to adjust the drawing code later on to put the level where it looks best.

Grab the player. Most of the same functionality will need to be applied to the player as well, so it would make sense to try to use one class to represent both of them.

An entity can exist in one of three states, and things happen differently to that entity depending on that state. If an entity is alive, things happen normally. If the entity is hit enough to kill it the ghosts or touched the player , its state gets switched to Dying.

Once the death animation is over, the entity is Dead, and several things can happen depending on the type of entity. If the player is out of lives, the game is over and the end game screen is displayed. The Direction enum is self-explanatory. The ghosts can move in any of the directions. The player can also move in any of the directions but can shoot in a different direction.

As the player completes levels, the ghosts will speed up. This is our entity for now. Listing public class EntityManager: Player, new Vector2 this. Ghost, new Vector2 Begin SpriteBlendMode. X, int entity. Y, entity. Height , new Rectangle entity. CurFrameX, 0, Chapter 3 entity. Height , Color.

Browse more videos

CurFrameX, 0, entity. If we start it off with a sizeable number and reuse the objects of dead ghosts for new ghosts, instead of removing and constantly adding objects, this might be a little more efficient. In our Initialize method we add the player and four ghosts. The last two variables are necessary so that a rectangle is drawn in the correct location in the texture to draw the right frame in the animation.

Listing public class FrameRateCounter: ToString , new Vector2 32, 32 , Color. The Update method handles the calculation for determining if enough time has elapsed to get the frame rate. The result is a smaller file that takes up less space and loads quicker. We will get the score from the EntityManager. Right now we just have a placeholder. The countdown is another easy piece. We already have the timer in place in our Update method; we just need to add some code: Final score: ToString ; messageBox.

Once the game is over, we display the final score and take the player back to the main menu. Feel free to go back over it from time to time. Chapter 4 Input At the end of the previous chapter we had a game running that displayed our player character and some ghosts. Their functionality is encapsulated into classes named, strangely enough, Keyboard, Mouse, and GamePad. Input devices can have two kinds of controls — digital and analog.

Digital controls can be in only one of two states — on or off. Keys on a keyboard are examples of digital controls as are the buttons on the mouse and the buttons and D-pad directional pad on the Xbox controller. Analog controls can have a value within a specific range.

The sticks and triggers on the Xbox controller and movements of the mouse return values within a range. The Xbox controller sticks return a floating-point value between —1. Mouse cursor values are returned in pixels. The following table provides a brief comparison. This is useful since the GamePad class can be used for a variety of devices. Figure shows the members of the structure. The types of devices can be found in the GamePadType enum value of the structure. The following values are possible: The SetVibration method is set up as follows: The leftMotor and rightMotor float values can be between 0.

To see this in action, start a new project and drop the following in the Update method: Abs xStick2 ; GamePad. SetVibration PlayerIndex. One, xStick, xStick2 ; Run the project and move the two thumbsticks along the X axis.

The left stick controls the left motor and the right stick controls the right motor. You can feel the difference between the two motors; the left is a slower, harder vibration, while the right is a faster, softer one. The only tricky part is dealing with the special keys — Ctrl, Alt, and Shift in conjunction with the regular keys. The SetPosition method is useful if for some reason you want to take control away from the player and position the mouse yourself.

This could be useful for something like a tutorial where you show the player where to move the mouse or indicate an object that should be clicked on. The WindowHandle property allows you to specify the window handle for which mouse data will be captured.

State Classes In order to get the input from a device you have to poll the device. That means capturing a snapshot of the device and the value of all of its controls every frame. You do this using the GetState method for the device you wish to look at. Each State class has different members, however.

Each of these members is a ButtonState enum value that has two possibilities, Pressed and Released. The DPad member is another structure set up exactly the same; it has four ButtonState type members in a structure for each of the four directions in the D-pad.

The IsConnected member is self-explanatory. PacketNumber is an integer value that you can use to determine if the state of the device has changed, rather than checking the controls themselves.

So you could do something like: Listing if GamePad. Each is a Vector2 data type where the X and Y members will be a value between —1. One major difference in the GetState method for the gamepad is the optional parameter that can be passed for the dead zone. The Triggers property is a structure with two members, Left and Right. Both are float data types with values that can be between 0. The IsButtonUp and IsButtonDown methods are simple helper functions that make it a bit easier to check a button instead of using the Buttons property.

These methods are new to the 2. Either way will get the job done, however. KeyboardState The KeyboardState structure looks like the following: The GetPressedKeys method returns an array of keys that are currently being pressed.

The this member allows you to get the state of any key on the keyboard, like so: Figure As you can see from the members of the structure, it handles a bit more than your basic mouse.

The MiddleButton property on a two-button mouse will map to the clicking of the scroll wheel if the mouse has one. You might as well just watch a movie in that case. These are the basic steps in controlling sprites: At the minimum this would probably be a Vector2 or individual X and Y coordinate variables. You basically have two types to choose from — rectangle collision detection and per-pixel collision detection.

For example, suppose the entities in your game are circles. Rectangular collision detection is going to give you some invalid collisions: Figure Figure Unless the action in the game is very fast, your players will notice this at some point and wonder why the game is broken.

Figure Name them bluecircle. You could call them whatever you want but the following code expects these names. Note that these images are included in the Chapter 4 file. Add the shapes to your project and add the following declarations: Input Next, add the following to the constructor: We create our array of sprites, which will be filled next.

Now add the following to the LoadGraphicsContent method: Load "whitecircle" ; content. Load "whitesquare" ; content. Load "bluecircle" ; content. Load "text" ; Nothing extraordinary here. We use white and blue shapes simply to show which shapes can be selected.

Exit ; if state. Update gameTime ; After the check to see if the project should exit, we do a check to see if we need to switch between shapes.

We then update the movement of the current shape. Doing so, however, means that the check for a collision will not be as accurate as it could be since the sprite will already have been updated before doing the check.

We then loop through and draw our sprites. Bottom, 0 ; if box1. The BoundingBox structure has built-in functionality for checking for the intersection of itself and other BoundingBox objects so we create two instances of the structure based on the Rectangles of the sprites.

If the call to the Intersects method of the first BoundingBox returns true, meaning we have a collision, we return a string that tells us which two sprites intersected. Notice that it returns after the first detected collision. You could modify it to return all the detected collisions by simply concatenating a string with the sprites that have collided.

Note that the constructor for the BoundingBox takes two Vector3 parameters, meaning you can use the object to do 3D collision detection. We simply pass a zero for the z element of each Vector3.

Another note here is that the Intersects method of the BoundingBox has a handful of different overloads to give you a bit more flexibility in your checking. The following figure shows all the versions that are available: Figure Input Per-pixel Collision Detection Per-pixel collision detection is much more accurate than rectangular detection, but more costly in terms of processing.

Implementing per-pixel collision detection in our previous sample is a matter of a relatively minor change in the CheckForCollisions function: We send these arrays along with their corresponding rectangles to the function.

Lastly, add the Intersect function: Max rect1. Top, rect2. Min rect1. Bottom, rect2. Left, rect2. Right, rect2. We want to check just the minimum amount of data we have to in order to determine if a collision has occurred. We check each pixel in the two Color arrays to see if their alpha value is 0. If both are greater than 0, we have an overlap in the actual sprites, which means a collision has occurred.

We return true to the calling function. If we make it all the way through the loop without returning, it means each pixel in the entire area of intersection contains only one color or is transparent, and no collision has occurred. The collision detection now works correctly. Input Figure Transformed Sprite Collision Detection What we have currently is great if the sprites never change orientation. Check the resources in the appendix for some suggestions. The Draw method has changed slightly. The following replaces the code between the SpriteBatch Begin and End calls: Y , null, Color.

We added a line to draw the bounding rectangle around the rotating sprite and added a new Draw call for the overload to handle rotation. The CheckForCollisions function has changed drastically, as one would expect.

Replace the code between the two Color array declarations and the return line with the following:Transform Vector2. DrawString ScreenManager. In our Game object we create an instance of the component, add it to our GameComponents list, create an instance of the service, and add it to the Services list while tying it to the component: The big change in Game Studio for the typical.

Michael Morton is a hobby game developer of over 16 years with experience in a gamut of graphics technologies and implementations. Texture Same as Deferred mode, except sprites are sorted by texture prior to drawing. Figure What we really need is a way to have SpriteBatch draw the background of the image transparently.

Listing public class EntityManager: