My friend John has been working on a WebGL game for some time now, and he’s decided to do a kickstarter for it. I’ve contributed a few bits of code and a dash of inspiration to this project. Check it out!
Well I usually don’t make New Year’s resolutions. That way I don’t have to deal with any of the disappointment of not following through. However, this year for some reason I’m inclined to make a few. I have been inspired and motivated to get better and smarter by stuff like this: Idea Experiment and Developer Book Club. Not that I’m not always about learning new stuff, but I guess those sites (and others) have motivated me to post this at least and try to hold myself accountable.
Maybe there should be more? Dunno, I’ll just edit this post and add some if I think they are needed. I had some general “ideas” but I think those are prolly gonna be best for the idea generator time.
Welcome to the second tutorial in a series on XNA Game Development. In the first tutorial we learned how to get all of the tools needed and create the basic solution, as well as a little about game loops. Now we’re going to do something much more interesting than just displaying a blue screen. We’re going to display an image on the screen, and we’ll make it move around.
So let’s build off of the previous solution, or create a new one if you don’t have that.
Ok, so first off we need an image. For the purposes of this tutorial we’ll just grab any image from a quick search on Google. I have found a lovely image of a cartoon cat. That should do for now. Take your image and drag it over the Contentproject in your solution. It should appear there as part of that project now. In XNA images are called Textures. There are both 2D and 3D textures, this is a 2D texture. In order to use the image in a game we need a reference to a Texture2D object. In the code the Texture2D object keeps track of all of the pixels in an image file. In order to get the data from the file into the object, we need to open and load the file. The Game class that we have derived from comes with a content manager built in. In the LoadContent method is where we will want to get the information from the image file into our texture object.
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D catTex;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
For now we have just created the Texture2D catTex as a private member of our Game class. Next in the LoadContent() method we will load the data.
///
<summary> /// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
catTex = Content.Load("cat");
}
Notice that we do not need to provide the file extension. Because there is only one file in the Content folder named “cat” XNA just pick that one. If we had cat.png and cat.jpg both in there, then we would need to specify. We can also create folders inside the content project in order to better separate the various types of content out. For now we can keep things simple, but later we will want to do this. Once a project gets bigger managing your resources will become more important.
Ok, now that we have loaded the cat image into memory, lets display it on the screen. Everything that we want to show on the screen goes in the Draw() method.
///
<summary> /// This is called when the game should draw itself.
/// </summary>
///Provides a snapshot of timing values.
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
spriteBatch.Begin();
spriteBatch.Draw(catTex, Vector2.Zero, Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
If you noticed before during the LoadContent() method that we instantiated a new instance of the spriteBatch and wondered what that was, now is the time to find out. The SpriteBatch is a special built in shader for XNA optimized for rendering textures to the screen. In game development when we render textures to the screen (and make them move about) we call them Sprites. A shader is a special program that gets executed on the graphics card telling it how to render. All modern graphics programming is done through the use of shaders. In the code above first we called spriteBatch.Begin(). Rather than drawing each instruction one at a time, you can batch together all of them into one call. We tell the spriteBatch to start paying attention, all of the following commands will be for the graphics card. When we are done, we tell it spriteBatch.End() so that it knows we have finished and can go ahead and send the instructions to the graphics card.
The Draw() method has several overloads, in this one the first thing it expects is a reference to a Texture2D object; i.e. which image to draw. The second parameter is the position on the screen that we want to draw the image. It is expecting a Vector2. A Vector2 represents a 2 dimensional vector, x and y coordinates. Beyond simply storing the x & y, you can perform all sorts of vector mathematics on them. Vectors are extremely important and something that you will need to use a lot. For now just know that I put in 0,0 for the coordinates, which is the upper left corner of the screen. The third and final parameter of this overload is a Color. The color is used to tint the image. Telling the draw method to use White will render the image as it is. It is like shining a light on the image in the real world, white light would reflect off of the surface back to us and we would see it as it was. If we had a red flashlight, the color would blend in with the colors of the image and only tint it red. Tinting can be a very useful technique, but for now we’ll just render it as is.
Now that we have that code, go ahead and launch the program in debug mode and you should see your image rendered onto the screen!
Ok, while that is exciting, I think that we’ll want to do something a little more interesting. Games do much more than just render images to the screen. Let’s make this cat move around! In order to do that we need to update the position that we draw it on the screen. First we’ll add a Vector2 to our game class so that we can keep track of the position at a higher scope from the Draw method. We’ll have it default to [0,0] still just like our old one, and then down in the Draw call we’ll replace Vector2.Zero with our new position value.
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D catTex;
Vector2 catPos = Vector2.Zero;
public Game1()
...
spriteBatch.Draw(catTex, catPos, Color.White);
The Update() method is where we want to perform any of our calculations that are not directly about drawing things on the screen. You’ll notice that there is already a little bit of code in that method, it is testing the gamepad to see if the Back button has been pressed. When the back button is pressed, the game exits. XNA has built in classes that can be used to check various types of input devices, the keyboard, gamepad, mouse, etc. Just like they are checking the GamePadState, there is also the KeyboardState.
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// TODO: Add your update logic here
KeyboardState kbstate = Keyboard.GetState(PlayerIndex.One);
GamePadState gbstate = GamePad.GetState(PlayerIndex.One);
if (kbstate.IsKeyDown(Keys.Left))
{
catPos.X -= 1;
}
if (kbstate.IsKeyDown(Keys.Right))
{
catPos.X += 1;
}
if (kbstate.IsKeyDown(Keys.Up))
{
catPos.Y -= 1;
}
if (kbstate.IsKeyDown(Keys.Down))
{
catPos.Y += 1;
}
catPos = Vector2.Add(catPos, gbstate.ThumbSticks.Left);
base.Update(gameTime);
}
Since we want to eventually use this on the Xbox we’ll get both the keyboard state and the gamepad state. By default Update() is called 60 times every second. Each time it is called we will check on the status of the input devices. For the keyboard we’ll use the arrow keys. Left and right modify the X-Axis and Up and Down modify the Y-Axis. For the gamepad we will use the Left Analog stick. From the tests there you can see that we are modifying our cat’s pos (paws?). Since Update() is called before Draw() it will change where the graphics card is told to render the image to the screen. Since every frame we are moving it slightly it will give the illusion of floating across the screen. In reality we’re just drawing a still image over and over in a slightly different spot. It’s also important to note that in screen coordinates the top of the screen is Y Zero and Y moves positively towards the bottom of the screen. So in order to move “up” we subtract from Y. On the X-Axis the left side of the screen is X Zero and X moves positively to the right. It’s perfectly fine and possible to set our image to coordinates that are outside of the screen. If you run the program now you will see that using the arrow keys we can make the cat go off the screen or in any direction that we want.
So now we’ve taken our first steps into something that is much closer to a game than just clearing the screen blue, but from here the sky is the limit! In the next tutorial we’ll take a look at rendering multiple sprites to the screen, utilizing tint, drawing text, basic collision detection, and some “AI”. For this tutorial you can grab the all the files HERE.
Following along with the theme from Desert Code Camp, I have decided to start writing a series of XNA game development tutorials. This will be the first one, and will start at the very beginning.
XNA is a game development framework created by Microsoft that has access to various game APIs through .NET. It can be used to create games for the Xbox 360, Windows Phone 7, and Windows PC. The framework provides classes and utilities to access various areas of games such as 2D and 3D graphics, sound, networking, and live services. In order to develop for the Xbox 360 and / or distribute games created on Microsoft’s App Hub, a $99/yr developer fee is required.
In order to develop using XNA you need to use Visual Studio 2010. Currently you can choose between C# and VB. The Express editions (free) will work fine for this. So first thing, download and install it. Personally, I prefer C# so (at least initially) all of my tutorials will be in that context. I doubt the translation between is terribly complex. Once that is installed you will then need to install the XNA Game Studio, which at the time of this writing is at version 4.0 Refresh. Here are the links, I’ve included the runtime distribution as well, for development, you need the first one.
XNA Game Studio 4.0 Refresh
Download page – http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=27599
Direct download link – http://download.microsoft.com/download/E/C/6/EC68782D-872A-4D58-A8D3-87881995CDD4/XNAGS40_setup.exe
XNA Framework Redistributable 4.0 Refresh
Download page – http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=27598
Direct download link – http://download.microsoft.com/download/5/3/A/53A804C8-EC78-43CD-A0F0-2FB4D45603D3/xnafx40_redist.msi
Now that you’ve got the tools installed, it’s time to fire up Visual Studio and create a new project.
You will notice that there are a few different project templates to choose from, for now go ahead and pick Windows Game 4.0. Even if you want to develop for Xbox 360 it’s best to start with this type of project. You can develop most of the time in Windows, and then easily switch over to the Xbox when needed. Visual Studio will create for you a somewhat bare bones solution so that you can get started!
There are two types of projects that will be created, the first is the main game itself, and the second is a Content project. In the content project is where all of your games assets will go. Anything like images, sounds, 3d models, game levels, etc. are considered content and will go in there. First let’s take a look at the code.
You’ll notice at the top that by default several libraries have been included:
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media;
These are all of the major XNA libraries. Each one covering a major aspect of the game application. For the most part they should be self explainatory, but we’ll go into them in more detail later. Next you’ll see the basic layout of a game. If you are new to any kind of game development the concept of a game loop might also be new. Normally a program is executed from top to bottom, and then when it goes past the final instructions it exits. For a game, obviously this isn’t desired behavior. So at some point we need to make sure that the program will keep running until the player decides to quit. In order to achieve this, you setup an infinite loop. At a basic level, it’s something like this:
while(true) {
// play!
if(done) {
break;
}
}
Behind the scenes it’s a little bit more complicated than that, but that is the general idea. In the base framework there is a Game class from which your game, Game1 is being derived. When the application starts an instance of your game class will be created. It runs the Initialize and LoadContent methods and then begins to loop. Every loop two methods are called: Update() and Draw(). Update by default will be called 60 times every second. Draw will be called as many times as possible. In order to ensure that Update maintains a consistent frame rate, sometimes the Draw call will be skipped. In order to have smooth animations and other timings you want to follow the names of the methods, update any of your entities in Update, and draw them in Draw. Here’s what they look like:
///
<summary> /// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
///Provides a snapshot of timing values.
protected override void Update(GameTime gameTime) {
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// TODO: Add your update logic here
base.Update(gameTime);
}
///
<summary> /// This is called when the game should draw itself.
/// </summary>
///Provides a snapshot of timing values.
protected override void Draw(GameTime gameTime) {
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
base.Draw(gameTime);
}
As you can see, they’ve placed some TODOs there for you to start coding away. In the Update method they are testing the input from the gamepad for the Back button being pressed, and if it is then exit the application. This is because if you were to send this application over to the Xbox it’s much harder to exit an application if there isn’t a provided button. You’d have to use the exit to dashboard feature to break out. In windows, you can simply click the standard window close button.
In the Draw application they are telling the graphics card to clear the screen to a lovely CornflowerBlue color. So every time, at least 60 times a second the game is checking to see if any buttons are pressed on the gamepad, and as many times as possible it is clearing the screen to blue. In order for things to render onto the screen they have to be drawn over and over. If you run this application, you should see this:
Well, there’s your first game. It doesn’t do anything, and it isn’t very exciting (to most), but it is indeed a game nonetheless. From here you can start to add graphics and sounds and game logic until you have the game of your dreams.
That’s it for the first tutorial, in the next one we’ll cover rendering an image to the screen and making it move around!
I gave a talk today at the Desert Code Camp on XNA 4.0 Development Basics. It was my first time presenting at any sort of event. I think overall it went pretty well, tho I had a few issues. The talk was only an hour long, and I found myself being able to cover less than I had thought. I think that in the near future I will be posting some tutorials based around this, so stay tuned.
Thanks to all those who attended, as promised here are the materials from the talk.
Lately I’ve been playing Minecraft a lot. Not only is it a fun game, but I have been working on some voxel type things myself, and I think that it’s important to be knowledgeable about the main game. (how can I create a game like it if I’m not an avid player?) Normal single player tends to get boring however, especially in the vanilla game. There are plenty of interesting mods, but even with that you will eventually crave some sort of community interaction. Another thing that the community has come up with are special maps and game types that you can play. Most of them are driven via the forums and rules and scoring are based pretty much on the honor system.
One type in particular I have found to be very interesting, that’s the Chainworld or “Pass It On”. Basically how it works is that one person starts playing the single player game. They play for an hour or two, and then zip up the save file and upload it to the forums. When you are ready to participate, you create a post and mark it “TAKEN”. Then you download the file and play for a couple of hours. While you’re in the world you get to see what your predecessors have built and found. When you are done, zip up the save folder and re-upload it for the next person. Then you mark your forum post as “RETURNED” and make a few comments about what you did and any notes that you might have for the next person. The rules are usually made up by the person who starts the chain world, but they are usually very similar: Don’t cheat, Don’t destroy other people’s creations, basically, just don’t be an ass. Ultimately, you can always revert to the previous “good” player’s run in the event that a “bad” player gets ahold of it.
I think that for a sandbox world this type of gameplay should be integrated into the game itself. Much like choosing CTF or Deathmatch you would choose Chainworld. From there a server can manage a list of worlds. Instead of having to monitor a forum post however the game could checkout the file automatically and download it into your play space. An in game timer system could watch the clock for you while you play, and automatically upload and check the map back in. There could even be other game manage features like instead of a time limit, give a life limit or something.
Of course in true multiplayer you could have a similar experience except that the players would potentially be there at the same time. I think there is still something of an added mystery with the single player version, and you don’t have to worry about lag.
Here are a couple that I’ve played on:
http://www.minecraftforum.net/topic/586880-passiton-tayas-edition/
I’ve been working on this game for about a year now, and I haven’t posted about it before… why? Dunno so here we go. The game is called For the Moon King. It’s a top down twin stick shooter. Here is a screenshot of the almost complete main menu. The idea is that the little elf travels around to the various spots on the map for each item in the menu that is in the lake.
Please like us on Facebook! Don’t do it for me, do it For the Moon King
I went to the jQuery Conference in Mountain View, CA a little while ago. It was a great experience, and I think that I learned quite a bit. When I got back, I gave a short presentation at work on some of the highlights. Here are my slides that I used for anyone who is interested. Thanks goes to @ajpiano for the base template.
Well, I have been interested in Voxels and Volumetric rendering for quite some time. I have also been following the game Minecraft for a very long time. Well, I decided to start working on my own block engine finally. It took quite a bit of research but I finally understand how it’s done (well most of it). So now a couple of friends of mine and I are working on creating a version for the Xbox 360.
I recently have been working on a simple “old school” rpg game for XNA. One of the features that I want to have is scrolling text for combat and other messages that are given to the player. What I am talking about might look like this:
You swing at the goblin and hit for 8 damage.
Well, there isn’t any built in method to draw text to the screen and have the colors change in one string. Pretty much the only way (or at least the easiest way) to accomplish this is to use multiple DrawString calls on the SpriteBatch. When thinking about that I didn’t think it would be a terribly difficult task, but I decided to do a google search for any already made solutions. I found an article on the XNAWiki called Inline Color Code Processing that claims to (I haven’t tried it) do the trick. When I examined it though, I found that I couldn’t be happy with their implementation. They chose to define a set number of colors and then reference them in the string using an integer index. That to me seemed very limited, and even though my project is simple, I’d rather not hard code in a bunch of colors. What I wanted is to be able to type in a color in the string and have it parse out to the color I wanted, much like HTML or BBCODE would work. The best way I could think of to do this is using HEX values, just like HTML or CSS would work. Unfortunately, getting a color from HEX is another thing that isn’t built into XNA. So, back to google and I found this blog that had the extensions I needed already worked out! Ok, fantastic, now the final piece, I just needed to write up a function to display the text. It actually ended up being pretty easy and perhaps it’s not the best implementation, but it works perfectly. To use it, you setup your string like so: “You attack the [color:#FFFF0000]goblin[/color] and hit for [color:#FF00FF00]8[/color] damage.” Of course, just as the extension is converting the HEX to actual colors, you can convert the colors to HEX when you are making the string and use some of the built in colors like Color.Red.ToHex(true).
public static void DrawColorFormattedText(SpriteBatch spriteBatch, SpriteFont font, Vector2 position, string text)
{
Color defaultColor = Color.White;
// only bother if we have color commands involved
if (text.Contains("[color:"))
{
// how far in x to offset from position
int currentOffset = 0;
// example:
// string.Format("You attempt to hit the [color:#FFFF0000]{0}[/color] but [color:{1}]MISS[/color]!",
// currentMonster.Name, Color.Red.ToHex(true));
string[] splits = text.Split(new string[] { "[color:" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var str in splits)
{
// if this section starts with a color
if (str.StartsWith("#"))
{
// #AARRGGBB
// #FFFFFFFFF
// #123456789
string color = str.Substring(0, 9);
// any subsequent msgs after the [/color] tag are defaultColor
string[] msgs = str.Substring(10).Split(new string[] { "[/color]" }, StringSplitOptions.RemoveEmptyEntries);
// always draw [0] there should be at least one
spriteBatch.DrawString(font, msgs[0], position + new Vector2(currentOffset, 0), color.ToColor());
currentOffset += (int)font.MeasureString(msgs[0]).X;
// there should only ever be one other string or none
if(msgs.Length == 2)
{
spriteBatch.DrawString(font, msgs[1], position + new Vector2(currentOffset, 0), defaultColor);
currentOffset += (int)font.MeasureString(msgs[1]).X;
}
}
else
{
spriteBatch.DrawString(font, str, position + new Vector2(currentOffset, 0), defaultColor);
currentOffset += (int)font.MeasureString(str).X;
}
}
}
else
{
// just draw the string as ordered
spriteBatch.DrawString(font, text, position, defaultColor);
}
}
And here it is, pics or it didn’t happen