XNA extension methods page

January 24th, 2010

Just a short note to let you know that I will gather my extensionmethods on a separate page with sample usage for handy reference.

XNA Pixel Robots library

January 20th, 2010

A while ago I came across Dave Bollinger's PixelRobots and PixelSpaceships:

Unfortunately his website is gone now :-(, but his work has not been in vain, as this C# version lives on :).

His website is still available on the WayBackMachine, so you can go look at the algorithm for pixel robots and pixel spaceships. In case they ever disappear, here's a zipped PDF print.

Dave, if you're out there, I hope you don't object to me storing your lost treasure for the rest of the world to enjoy your creation :)

He has invented a way of generating simple, random robot-like or spaceship-like sprites. His code will generate many different versions of the millions and millions of possible variations of robots and spaceships. I really liked the idea, and thought that it would be very nice to have an XNA implementation for anyone who needed generic spaceships or robots in a game. So I created an XNA version from his description.

You don't have to understand the internals of neither Dave's code or my API to use this code, as everything is wrapped up in simple methods. But all the helpermethods and variables are available for use if you want to create something more advanced.

It can be as simple as this:

//create two bitmaps scaled by 5 with different colors
Bitmap spaceship = PixelMaskGenerator.GetCompletedRandomSpaceshipImage(5, Color.CornflowerBlue);
Bitmap robot = PixelMaskGenerator.GetCompletedRandomRobotImage(5, Color.LightGreen);

The above code would generate the following two images:

If you'd rather generate SpriteSheets and then use them as Content files instead of creating the spaceships runtime there's also support for that. The spritesheet below was created with the following code:

//create spritesheet
//scaled 3 times, 10 rows and 10 columns
//using spaceships in CornFlowerBlue
Bitmap spritesheet =
PixelMaskGenerator.GenerateRandomSample(3, 10, PixelMaskType.SpaceShip, Color.CornFlowerBlue);
spritesheet.Save(@"C:\spritesheet.png");
spritesheet.Dispose();

Samples spaceships

And then if you need to convert the Bitmaps to Texture2D runtime, it can be done in XNA 4.0 with Florian Block's code:

//Converts a Bitmap to a Texture2D
//Code found here:
//<a href="http://florianblock.blogspot.com/2008/06/copying-dynamically-created-bitmap-to.html):">http://florianblock.blogspot.com/2008/06/copying-dynamically-created-bitmap-to.html):</a>

private Texture2D BitmapToTexture2D(GraphicsDevice dev, System.Drawing.Bitmap bmp)
{
    Texture2D customTexture = new Texture2D(this.GraphicsDevice, bmp.Width, bmp.Height);
    BitmapData data = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);

    // calculate the byte size: for PixelFormat.Format32bppArgb (standard for GDI bitmaps) it's the hight * stride
    int bufferSize = data.Height * data.Stride; // stride already incorporates 4 bytes per pixel

    // create buffer
    byte[] bytes = new byte[bufferSize];

    // copy bitmap data into buffer
    Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);

    // copy our buffer to the texture
    customTexture.SetData(bytes);

    // unlock the bitmap data
    bmp.UnlockBits(data);

    return customTexture;
}

Code
The Download code is available here.
The solution includes three projects:

  • PixelRobots is the main project is the project which contains all the code needed to generate SpaceShips, Robots and SpinedRobots (robots that are ensured a cohesive spine) for your game.
  • ConsoleTester is a consoleproject which goes through step-by-step what is done behind the curtains. It saves the generated images to disk and displays them in an HTML page.
  • TestingPixelRobotsInXNA is a little XNA demo which lets you generate spaceships with the left mousebutton and robots with the right mousebutton.

TestingPixelRobotsInXNA

I made a short video presenting the API in use in TestingPixelRobotsInXNA:

Hope it is of use to somebody - it was fun making :)
If you use it for something I'd love to see for what.

More links
Want your own PixelRobot Tee?
Want the code in PHP for your website?
Want to see the PixelRobot idea used in a windowsgame? (non-XNA)

MouseState ExtensionMethod

January 20th, 2010

Just a little helpermethod to get the mouse's position as a Vector2.

For those of you who still haven't gotten started with extension methods here's a quick writeup'n'sample

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace XNAFAN
{
public static class MouseStateExtensionMethods
{

///

/// Returns the mouseposition as a Vector2
///

/// The current MouseState /// The mouseposition as a Vector2
public static Vector2 GetPosition(this MouseState mouse)
{
return new Vector2(mouse.X, mouse.Y);
}
}
}

This way you don't have to convert x and y every time along the lines of
MouseState mouseState = Mouse.GetState();
Vector2 position = new Vector2(mouseState.X, mouseState.Y);

Instead you just add a reference to the code with the extensionmethod and this enables you to write:

Vector2 position = mouseState.GetPosition();

Nifty - eh...? :-)

Spritesheets galore!

December 18th, 2009

Just saw this post over at GameDev.net with a lot of links to spritesheets for use in YOUR game! :)

Here's a sample from the game 1945

SpriteSheet from the game 1945

SpriteSheet from the game 1945

BasicStarter – something to get you up and running with XNA :)

December 17th, 2009

basicstarterscreendumpBased on the input I received from my talk at Aalborg .Net User Group yesterday, I cleaned & commented my code and created a little XNA 3.1 Windows project called BasicStarter to download.

It is a simple start-out class for use in games for beginning XNA coders, has basic keyboard movement in four directions, fullscreen setup, black background.
It is possible to pause the game with "P"
It is possible to exit the game with "Esc"
The project also shows how a class called GameSprite which subclasses DrawableGameComponent is used to store image, position and speed of an object in a game.

Here is the class diagram. I like to get the gist of other people’s code this way Smiley

basicstarterclassdiagram

Some notable pieces of code for the beginner are:

How to get a direction from multiple keypresses
//create a variable to hold which direction to move
Vector2 movement = Vector2.Zero;

//alter the direction according to the keys pressed:
if (keyState.IsKeyDown(Keys.Down)) { movement += Directions.Down; }
if (keyState.IsKeyDown(Keys.Up)) { movement += Directions.Up; }
if (keyState.IsKeyDown(Keys.Left)) { movement += Directions.Left; }
if (keyState.IsKeyDown(Keys.Right)) { movement += Directions.Right; }

//use the combined movement from the keys
//to update the position of the XNA logo
//we multiply by gamespeed to get a reasonable speed onscreen
xnaLogo.Velocity = movement * gameSpeed;
Hope you like it - and send feedback if you can think of improvements :)

XNA talk at AANUG

December 16th, 2009

xnacrashcourse_firstslideJust came home from Aalborg .Net User Group (AANUG) where I had the pleasure of introducing around 20 coders to XNA. We talked our way through a little quick and dirty "Let's make a PNG move across the screen using the keyboard" to

  • Proper methods of subclassing DrawableGameComponent.
  • Using ElapsedGameTime to make animation smooth
  • Storing services in Game.Services so components can communicate
  • Etc.

All in all a fun evening with a keen crowd. Thanks to the XNA coders present who supplemented my presentation where I lacked knowledge (XBOX360 specifics and the Indie concept).

The PowerPoint is in danish - so no need to download it if you don't speak that language 😉

Xna præsentation

Silverlight experimental edition out :)

December 4th, 2009

Jesper Niedermann has ported Klima Konflikt to a SilverLight edition for web using the SilverSprite engine.

Klima Konflikt in a browser - SilverSprite style

Klima Konflikt in a browser - SilverSprite style

It's really cool that it is possible to create a game that will run in both a browser, on an XBOX360, a PC and a Zune. Of course with modifications, etc. but stil...

(And yes - I know that's been possible with Java for years using Applets ;-))

Check it out : )

Bought an XBOX 360 – just for playtesting :-)

November 4th, 2009

Xbox360full_500x526 Just bought a somewhat battered XBOX 360 cheaply online.

So soon we will have the XBOX version ready to rumble as well, now that we can playtest.
Since I don't have any other games for it, I guess I will be extra motivated to make Climate Conflict ever more interesting :)

The first thing I guess I will have to cope with is creating an adapter class which adapts to either keyboard or controller so the gamecode can stay clean and blissfully unaware of what kind of hardware is telling it to do something :) ... and then screen resolution will have to be handled gracefully of course.

Plug-n-Play pathfinding

November 4th, 2009

I once implemented the A* (A-star) pathfinding algorithm in Java, and was ready to do it again in C# for the Klima Konflikt game, but while Googling a bit for referenceimplementations I stumbled across Eric Lippert's very, very elegant solution.
He has basically created a class with a static generic method which will pathfind on anything if you just supply:

1) Items which can tell what their neighbors are - by implementing:
interface IHasNeighbours
{
IEnumerable Neighbours { get; }
}
2) A "Begin" and "End" item
3) A function which gives an estimate on the expected distance from an item to an item (WalledTiles in my case).
The distance can be calculated easily using the Pythagorean theorem.
4) [optional] A function which returns a cost for a tile (based on a weighting system you decide).

Here's the signature for the method:

static public Path FindPath(
Node start, Node destination,
Func distance,
Func estimate)
where Node : IHasNeighbours

It took me 20 minutes to implement, just because I am fairly new to the idea of the Func keyword. Thank you Jesper for walking me through it :)
Pathfinding takes approximately 46 ms on our 10x10 tile board.

Screenshot from the current version of the game

Screenshot from the current version of the game

A very, very elegant solution - thanks Eric!

Now in Widescreen :)

November 4th, 2009

Found the default WP theme (which I happen to like) in a wider format at http://www.cenolan.com/2008/11/wordpress-default-theme-1024-wide/.

Nice and easy to install - and with quite a bit more space for your XNA reading enjoyment.