Archive for the ‘XNA’ Category

Simple XNA Progress Bar

Friday, April 3rd, 2009

I recently needed a dead simple progress bar, where I could give it a display rectangle, min, max, and a value and show me something in game, but couldn’t find anything online. I ended up writing it myself, and thought I’d share what I came up with.

My goal was to create a single file I could drop into a project to allow me to draw a progress bar. All the projects I found involved using a texture as a separate file. I knew from a previous project that you could create that texture in-memory using the Texture2D.SetData() function, and that’s what I did.

I also wanted to provide a double border so I could put the progress bar on top of any background without having its border look invisible. If you’ve ever seen closed captioning disappear because of the background color, you know what I mean. But since not everyone needs a double border, I made sure you could turn it off.

Anyways, here’s and example of what you can do with the progress bar. (download the project for this at the bottom).


So the simple way to get a progress bar into your game is this:

1. Get the source code.

2. Add ProgressBar.cs to your XNA project. Note that I wrote this in 3.0, so make sure you’re on that version or higher.

3. Create an instance of a progress bar in your game1 class;

UI.ProgressBar progressBar;

4. In your LoadContent() function, set it to a new progressBar, and provide the rectangle you want it to lie in. You can also set the minimum, maximum, and value member variables here. The defaults are 0, 100, and 0, respectively.

progressBar = new UI.ProgressBar(this, new Rectangle(10, 10, 300, 16));
progressBar.minimum = 0;
progressBar.maximum= 10000;

5. In your Update() function, update the value of your progress bar if necessary, and then call the progress bar’s Update() function, providing the gameTime (gameTime is not currently used in the progress bar code, though).

progressBar.value = character.health;
progressBar.Update(gameTime);

6. In your Draw() function, call progressBar.Draw(), specifying a spriteBatch. Make sure you’re already called SpriteBatch.Begin() before calling the progress bar Draw() function.

progressBar.Draw(spriteBatch);

And that’s it!

Now, I’ve put quite a few customizable pieces in there. They are all commented in the progress bar code, in the “public members” region.

The one I’d like to talk about is the orientation. You can specify that the progress bar be vertical or horizontal, and in which direction it fill. This is specified at creation time in the ProgressBar constructor. See the orientation member variable for more info.

Here’s a list of the public variables in there now:

float minimum – Minimum value of the progress bar. Default is 0.0f.
float maximum – Maximum value of the progress bar. Default is 100.0f.
float value – Current progress value.

Int32 borderThicknessOuter – Outer border thickness. This is drawn within the bounds of the progress bar. Default is 3.
Int32 borderThicknessInner – Inner border thickness. This is drawn within the bounds of the progress bar. Default is 2.

Color borderColorOuter – Outer border color. Default is Gray.
Color borderColorInner – Inner border color. Default is Black
Color fillColor – Color of the progress section of the bar. Default is Dark Blue.
Color backgroundColor – Color of the background (unfilled) section of the progress bar. Default is White.
Orientation orientation – Gets the orientation of this progress bar. Set at creation time.

Note that you should be careful with the border thickness values. I didn’t add any checking to make sure the border isn’t overcrowding the actual progress bar. You could theoretically have a progress bar that is all border if you set the thicknesses too big.

Ok, so here’s a sample project. Hold space bar if you want to pause.

And here’s the bare ProgressBar.cs file (zipped, of course).

Farseer Physics

Saturday, April 26th, 2008

I’ve been playing with the Farseer Physics engine lately. It’s a physics engine for XNA and Silverlight. I’ve been toying with the idea of a game involving spiderman-like web swinging. You have a character, and he can fire a grappling hook from either hand. He the uses this mechanism to swing about. What I’ve got so far is a box that can fire a single grappling hook and swing about the screen. It’s taken me 3 hours or so to get this far (which i think is pretty quick), and I attribute the quick spin-up to how easy the Farseer engine is to use.

The only gripe i have is that it has basically zero documentation. And since this code has been around since 2006, I’m gonna guess no documentation is coming any time soon. The good news is they provide quite a bit of sample code, and the guy who wrote it seems to reply to just about every question people can think of on the codeplex boards.

Either way, i’m having some fun. I’ll post some code when I get there.

Finished with Conway’s game of life

Sunday, April 6th, 2008

Well, I’ve gotten what I want out of my attempt at writing Conway’s Game of Life. I was mostly using Conway’s as a reason to put together a menu system, and it has gotten me that. I posted my menu code here. So, with that in mind, here’s my code for Conway’s Game of Life. I built it using XNA GSE 2.0 in Visual Studio 2005. It’s a very humble implementation, and rather than making this more interesting, I’d like to spend some time with other more interesting projects. More to come on that as soon as I have something worth showing.

New Menu Code

Sunday, March 30th, 2008

Download source code for this project

Okay, It’s been busy at home lately. I’ve been moving it. But I’ve been trying to find a little time every day to work on my XNA stuff, and I’ve got a much more complete menu system now.

I’ve made some changes:

– The menu now shows a default “Return” choice at the bottom of each list. This can be turned off by setting the “showBackChoice” boolean.
– The menu now has two types of choices, Normal and LeftRight. Normal choice will show their child choices as a separate menu when they are executed. LeftRight choices will show their child choices as a list to the left of the parent choice when they are SELECTED.

I’ve also made the sample code show a bit more info in the console as you are viewing the menu. The sample code initializes the menu as follows:

mainMenu.AddChoice(“Choice 1”);

MenuChoice choice = mainMenu.AddChoice(“LR Choice”);

choice.AddLeftRightChoices(new string[] { “one”, “two”, “three” });

choice = mainMenu.AddChoice(“Sub Menu”);

choice.AddChoice(“Sub choice 1”);

choice.AddChoice(“Sub choice 2”);

mainMenu.ChoiceExecuted += new Menu.ChoiceExecutedHandler(ChoiceExecuted);

mainMenu.ChoiceSelected += new Menu.ChoiceSelectedHandler(ChoiceSelected);

mainMenu.ChoiceDeselected += new Menu.ChoiceDeselectedHandler(ChoiceDeselected);

So there you go. Pretty simple. If I make any more changes, I’ll be sure to post them. Possible changes could be:

– using a proper spriteFont to display the text (so we could use something besides Times new Roman).
– making background images actually work.
– something I overlooked….

I’ve realized as I’ve been working on this that is might have been easier to just implement it using a full on tree, rather than a bunch of sneaky lists.

Basic Menu

Sunday, March 16th, 2008

Well, it’s been busy lately, but I’ve got a solid start on the menu, so I thought I’d post what I have as a forcing function to make me clean up my code. You can grab the source here. To use the menu system, you need to an instance of the GameMenu in you code. You can declare this in you game class (don’t forget to put “using GameMenu;” at the top of your code”):

Menu mainMenu;

Then, in LoadContent(), initialize the menu, it’s choices, and any handlers you want to catch.

mainMenu = new GameMenu.Menu(this);

mainMenu.AddChoice(“Show Sprite”);

mainMenu.AddChoice(“Return”);

mainMenu.ChoiceExecuted += new Menu.ChoiceExecutedHandler(ChoiceExecuted);

Of course, ChoiceExecuted should be defined somewhere. I’ll get to that at the end. In your Update() method, call the game menu’s update function:

mainMenu.Update(gameTime);

And in the Draw() method, call the menu’s draw function:

mainMenu.Draw(gameTime);

If the menu isn’t visible, those functions will do nothing. To show the menu, you set the visible property to true. I do this in the Update method when the user pressed escape:

if (keyboardState.IsKeyDown(Keys.Escape) && !prevKeyBoardState.IsKeyDown(Keys.Escape))

{

mainMenu.visible = !mainMenu.visible;

}

And finally, when a menu choice is executed, you handle it as follows:

public void ChoiceExecuted(object source, Menu.MenuEvent e)

{

if (e.choiceString == “Show Sprite”)

{

mainMenu.visible = false;

}

else if (e.choiceString == “Return”)

{

mainMenu.visible = false;

}

}

All I’m doing in the sample code is hiding the menu, but you can do anything in there. There are also choiceSelected and choiceDeselected events, and they get fired in the current code.

My next update to this code should have the ability to navigate through menu pages, and the ability to give the user some left/right choices as far as options go (a “Sound On Off” menu choice, for example).

Menu System, Continued

Thursday, March 6th, 2008

Okay, the menu system is coming a long nicely. I’ve got it displaying on the screen where I want it, and it is doing the collision detection work to select options with the mouse and keyboard. I’ll save the events for tomorrow.

The only change to the below code is that you have to pass the Game class when you create the menu (I’ve created the menu system as a DrawableGameComponent):

menu = new Menu(this);

I’m using a bitmap font class that I got here to do the work of displaying the text. The only problem I can see with using this class is that it will force me into a certain font… It’s pretty well designed though, so it has made it a lot easier to get going. I’ll have to visit different fonts later. Right now, Times New Roman is my best friend.

Designing a Menu System

Wednesday, March 5th, 2008

Well, it’s 2am and I’ve been plugging away at what I think will be a useful menu system. We’ll have to just wait and see when I’ve got it finished. I’m basing the architecture on the way a TreeView works in C#, and my goal is that the following code will initialize a menu:

Menu menu = new Menu();

menu.AddChoice(“New Game”);

menu.AddChoice(“Load Game”);

MenuChoice OptionsMenu = menu.AddChoice(“Options”);

OptionsMenu.AddChoice(“Resolution”);

OptionsMenu.AddChoice(“Volume”);

menu.NodeSelectedEvent += new Menu.ChoiceExecutedHandler(ChoiceExecuted);

We’ll see what I end up with. Hopefully it won’t get too cluttered with code related to drawing the darn thing.

XNA – How to Disable Bitmap Magnification Blending (Blur)

Monday, March 3rd, 2008

In working on my code for Conway’s Game of Life, I ran into a problem with the default bitmap scaling behavior in XNA. I’m generating a bitmap that I scale to the size of the window. When this bitmap is displayed, it is shown as a blurry mess:


Removing that doggone blending is actually quite simple. You have to modify your spriteBatch.begin() call, and modify the graphics device settings immediately after, like so:

spriteBatch.Begin(SpriteBlendMode.AlphaBlend,

SpriteSortMode.Immediate, SaveStateMode.None);

graphics.GraphicsDevice.SamplerStates[0].MagFilter = TextureFilter.None;

The key in the spriteBatch.Begin() call is the SpriteSortMode. Setting this value to immediate causes any changes to the graphics device to be applied immediately. And we want to make a change, as you can see in the next line of code. I’m changing the magnification filter to TextureFilter.None because I don’t want it to blue anything. After this, you draw and scale your sprites like normal. The result looks like this:


ahh… much better!

Displaying a Mouse Pointer in XNA

Sunday, March 2nd, 2008

XNA doesn’t automatically show you a mouse pointer within the game window. Solving this is easy. First, you need a position for your mouse. You’ll also need a 2d texture to display as your mouse pointer. Declare this within your game class:

Texture2D m_mouseTexture;

Vector2 m_mousePos;

Be sure to initialize it to zero. For simplicity, I also generate a simple red square texture to use as the mouse pointer. I’m doing all of this in the Initialize() function. In my (very short) experience with XNA, you’d want to initialize textures in the LoadContent() function, but this is not loading from a file, so it’s safe to do it all in the Initialize() function like this:

m_mousePos = Vector2.Zero;

 

m_mouseTexture = new Texture2D(graphics.GraphicsDevice, (int)POINTSIZE, (int)POINTSIZE, 1, TextureUsage.None, SurfaceFormat.Color);

 

Color[] texture = new Color[POINTSIZE * POINTSIZE];

for (int i = 0; i < texture.Length; ++i)

{

    texture[i] = Color.Red;

}

m_mouseTexture.SetData(texture);

Now, in the Update() function, update your mouse position:

MouseState mouseState = Mouse.GetState();

m_mousePos.X = mouseState.X;

m_mousePos.Y = mouseState.Y;

And finally, in the Draw() function, draw your sprite in a spritebatch:

spriteBatch.Begin();

spriteBatch.Draw(m_mouseTexture, m_mousePos, null, Color.White, 0f,

        Vector2.Zero, 1.0f, SpriteEffects.None, 0f);

spriteBatch.End();

Grab the sample project for this here.

Conway’s Game of Life

Saturday, March 1st, 2008

I thought I should talk a little about the project I’m focusing on right now. I’m still spinning up on XNA, and I was reading an article somewhere recently that mentioned Conway’s Game of Life. I was never taught about this in school for some reason. What a wonderful little thing!

Anyways, I thought it would be fun to implement Conway’s Game of Life in XNA to give myself something tangible (in the software sense… what does that really mean, anyways?) to work on. I’ve already got a basic architecture done, but I want to write down some of the guidelines I’m trying to stick to. Just basic stuff, like:

What am I trying to learn?
– I want to learn about what it will take to implement a menu system in XNA.
– I want to learn about mouse interaction with an object (the game board) on the screen.

Which Game of Life algorithm should I use?
– a few are mentioned on the wiki page, notably hashlife. Since I’m not trying to learn about Game of Life specifics, I’m going to start with brute force with two 2d arrays (one for the current interation, and one for the next). It will give me a good quick start on my goal, and also give me a good baseline if I decide to optimize the algorithm.

What operations should I allow?
– a mouse click should turn a cell on or off. Hold and drag to fill or unfill cells under the mouse pointer
– spacebar should step to the next iteration.
– enter should run through iterations at the chosen speed (we’ll need a menu for that).

What should the menu contain?
– Options
– run speed
– window size
– colors?
– I’ll leave any other nifty stuff for later.

Things that would be very interesting to implement:
– the ability to move and zoom the camera around the grid with the mouse or keyboard
– some logic to move and zoom the camera automatically, and follow the most activity in the grid. One nasty corner case for this is any gliders that come off of the high activity areas. how do i know when to ignore them?

More to come later when I have more of this implemented.