Tag: GAME DEVELOPMENT

Zune HD Accelerometer Basics

Posted by – October 2, 2009

I was just messing around with my Zune HD while taking a short break from my main project when I thought I could port my TinyEngine to it in no time.

Sure enough, it took about 12 seconds.

In my dummy project I have Mr Tiny just smiling away in the center of the screen.

mrtiny

I wanted to get him to move around by just using the accelerometer. This was really simple.

I just call Accelerometer.GetState(); which returns a AccelerometerState. The AccelerometerState contains a Acceleration of type Vector3 which contains the direction of the accelerometer. I then just pass the direction of tilt to my engines Sprite Move command, as a Vector2.

Something like this

Vector2 accel = new Vector2(state.Acceleration.X, -state.Acceleration.Y);
    AccelerometerState state = Accelerometer.GetState();
    Vector2 accel = new Vector2(state.Acceleration.X, -state.Acceleration.Y);
    this.mrTiny.Move(accel * 100 * elapsed);

Clamp it to the screen

    this.mrTiny.PositionX = MathHelper.Clamp(this.mrTiny.PositionX, this.ScreenBounds.Left, this.ScreenBounds.Right);
    this.mrTiny.PositionY = MathHelper.Clamp(this.mrTiny.PositionY, this.ScreenBounds.Top, this.ScreenBounds.Bottom);

 

And there we have it, you can tilt your Zune HD to move around Mr Tiny.

Short but sweet uh?

The code is linked just below. I’ll be looking to do more Zune HD samples in the near future, as well as adding gesture support to TinyEngine.

Once I’m finished with my secret project.

Source Code (Includes Tiny Engine Source)

K.I.S.S – Fading between images with XNA

Posted by – September 6, 2009

In my first Keep It Simple Stupid (K.I.S.S) post I wanted to write about fading between 2 images.

Fading between 2 images is a very simple task using XNA, yet I’ve seen some severely over engineered solutions in the past. Here’s my take on the problem.

We need to fade from one image which is currently displaying on screen to another image we have stored in memory.

Here are 3 states of 2 images fading between each other.

The Start

blogimage1

The Fade

blogimage2

The Result

blogimage3

To keep it simple we use functionality within the XNA framework so we don’t have to write our own. This can be done using the SpriteBatch AlphaBlend which just happens to be the default option when calling Begin on a SpriteBatch.

Simply call Begin, draw the image currently on screen at a reduced alpha, then draw the image you want to transition to over the top with a alpha set to the other extreme.

I created a class which takes care of the drawing and alpha transitioning. Once we create an instance of the CustomImage class we must call Update, passing it the elapsed time since the last frame and also call the Draw method to draw the transition.

If there is no transition the CustomImage will simply draw the Image set at full opacity.

We define the amount of time to take in a transition in the constructor of the CustomImage or it can be changed via the TransitionTime property.

To start a transition just pass a Texture2D to the TransitionTo method. This will begin the process of fading between the two images and will completely switch over to the new image once complete.

Here is the full class implementation.

 public class CustomImage
{
    private float timer;
    public CustomImage(Texture2D initialImage, Vector2 position, Vector2 origin, float transitionTime)
    {
        this.Image = initialImage;
        this.TransitionTime = transitionTime;
        this.Color = Color.White;
        this.Rotation = 0;
        this.Position = position;
        this.Origin = origin;
    }

    public float TransitionTime { get; set; }

    public Texture2D Image { get; private set; }

    public Texture2D ToImage { get; private set; }

    public Vector2 Origin { get; set; }

    public Vector2 Position { get; set; }

    public Color Color { get; set; }

    public float Rotation { get; set; }

    public void TransitionTo(Texture2D image)
    {
        if (this.ToImage != null)
        {
            return;
        }
        this.ToImage = image;
        this.timer = 0;
    }

    public void Draw(SpriteBatch batch)
    {
        if (this.ToImage == null)
        {
            batch.Draw( this.Image, this.Position, null, this.Color, this.Rotation, this.Origin, 1f, SpriteEffects.None, 0);
        }
        else
        {
            int alpha = (int)((this.timer / this.TransitionTime) * 255);
            this.DrawImage(batch, this.Image, 255 - alpha);
            this.DrawImage(batch, this.ToImage, alpha);
        }
    }

    public void Update(float elapsed)
    {
        // We must be transitioning
        if (this.ToImage != null)
        {
            this.timer += elapsed;
            if (this.timer >= this.TransitionTime)
            {
                this.Image = this.ToImage;
                this.ToImage = null;
            }
        }
    }

    private void DrawImage(SpriteBatch batch, Texture2D texture, int alpha)
    {
        batch.Draw( texture, this.Position, null, new Color(this.Color, (byte)alpha), this.Rotation, this.Origin, 1f, SpriteEffects.None, 0);
    }
} 

&nbsp

To use this class we pass a Texture2D, a position, an origin and a length of time we want a transition to take.

Calling Draw will draw the image set until you pass a Texture2D to the TransitionTo method.

Here’s is the full Game code to show how I used this class in the sample which you can download at the end of the page.

 public class Game1 : Microsoft.Xna.Framework.Game
{
    private GraphicsDeviceManager graphics;
    private SpriteBatch spriteBatch;
    private SpriteFont font;
    private CustomImage image1;
    private CustomImage image2;
    private float storedTimer = 2;
    private KeyboardState currentKeyboardState, lastKeyboardState;
    private Vector2 imageSize = new Vector2(400, 300);

    public Game1()
    {
        this.graphics = new GraphicsDeviceManager(this);
        this.Content.RootDirectory = "Content";
    }

    private Vector2 ScreenSize
    {
        get
        {
            return new Vector2(this.GraphicsDevice.Viewport.Width, this.GraphicsDevice.Viewport.Height);
        }
    }

    protected override void Initialize()
    {
        base.Initialize();
    }

	protected override void LoadContent()
    {
        this.spriteBatch = new SpriteBatch(GraphicsDevice);
        this.font = this.Content.Load<spritefont>("Fonts/Arial");

		Vector2 position = new Vector2((this.ScreenSize.X / 4), this.ScreenSize.Y / 2);
        this.image1 = new CustomImage(this.Content.Load<texture2d>("Textures/Image1"), position, this.imageSize / 2, this.storedTimer);

		position.X += this.ScreenSize.X / 2;
        this.image2 = new CustomImage(this.Content.Load<texture2d>("Textures/Image2"), position, this.imageSize / 2, this.storedTimer);
    }

	protected override void UnloadContent()
    {
    }

    protected override void Update(GameTime gameTime)
    {
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
        {
            this.Exit();
        }

		this.lastKeyboardState = this.currentKeyboardState;
        this.currentKeyboardState = Keyboard.GetState();

		float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

		this.HandleInput();

		this.image1.Update(elapsed);
        this.image2.Update(elapsed);

		base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        this.GraphicsDevice.Clear(Color.Black);

		this.spriteBatch.Begin();

		StringBuilder instructions = new StringBuilder();
        instructions.Append("Space : Transition");
        instructions.Append(Environment.NewLine);
        instructions.Append("PgUp / PgDwn : Increase / Decrease Timer");
        instructions.Append(Environment.NewLine);
        instructions.Append(string.Format("Transition Time : {0}", this.storedTimer));

		this.spriteBatch.DrawString(this.font, instructions, new Vector2(25), Color.White);

		this.image1.Draw(this.spriteBatch);
        this.image2.Draw(this.spriteBatch);

		this.spriteBatch.End();

		base.Draw(gameTime);
    }

    private void HandleInput()
    {
        if (this.IsNewKeyPress(Keys.Space))
        {
            this.image1.TransitionTo(this.image2.Image);
            this.image2.TransitionTo(this.image1.Image);
        }

        if (this.IsNewKeyPress(Keys.PageDown))
        {
            this.storedTimer -= 0.25f;
            this.image1.TransitionTime = this.image2.TransitionTime = this.storedTimer;
        }

		if (this.IsNewKeyPress(Keys.PageUp))
        {
            this.storedTimer += 0.25f;
            this.image1.TransitionTime = this.image2.TransitionTime = this.storedTimer;
        }
    }

    private bool IsNewKeyPress(Keys keys)
    {
        return this.currentKeyboardState.IsKeyUp(keys) && this.lastKeyboardState.IsKeyDown(keys);
    }

    private void DrawImage(Texture2D image, Vector2 position)
    {
        this.spriteBatch.Draw(image, position, null, Color.White, 0, this.imageSize / 2, 1, SpriteEffects.None, 0);
    }
} 

 

You can download the sample project with complete working sample here

The Week in Code by Björn

Posted by – July 14, 2009

Björn (or boki) has written his 7th instalment of The Week in Code. Hit the RSS button and maybe he’ll feel obliged to keep it up and add some more. I’m in there 2 weeks on the trot by the way :D

Björn’s XNA Adventures

BRAINS – XNA A.I Library – Source Code

Posted by – July 12, 2009

image As mentioned in a previous post I have been working on an A.I library for use with XNA games. I have attached the latest source code to this post as well as the location to the SVN which I will be continuing to update.

If you do try it out and find any issues you would like to have fixed, please let me know and I’ll happily respond to requests. If anyone would like to contribute in the form of a patch or just contribute in the form of ideas and feedback, It’s all welcome.

Brains is only about 2 weeks old since I started the clean new project and it’s still very much a work in progress so there are still lots of features I could add to this middleware component to make it more useful.

Brains Source ZIP Download

Brains SVN Root

In the project is the main BRAINSFramework along with the debug AIRendering project. A Gamestatemanagement library for setting up a new game quickly and the AIDemos. There is also a very primitive Behavior tree designer which I’m currently working on making more friendly and feature rich.

I will be writing more comprehensive documentation in due course along with some articles to accompany the BRAINS library.

XNA & Game A.I – Where to begin

Posted by – July 8, 2009

I’ve been thinking a lot about writing some articles on using A.I in games with XNA but I just don’t know where to begin. I have to start somewhere so let’s get to it.

As previously mentioned I’ve been writing an A.I library for use with XNA games. It’s called Brains and it consists of a few building blocks to get you quickly up and running with an A.I prototype and just as simple to implement right into your game. It’s currently only in 2D but would not require too much modification to support 3D.

The Brains library is built up of a world map, an A.I agent and a behavior tree implementation.

The Map

A world map is made up of a grid. In it’s simplest form a world map could look like this

image

It would be made up of 1 grid which is 16 GridCells and have 4 columns and 4 rows of GridCells.

A more complex world might have over 100×100 GridCells in it’s map. Brains can split this into a cluster for you which will greatly increase the speed of path finding and other A.I techniques. As a simple sample we could have a map made up of 8×8 cells and have a cluster of 4 grids.

image image

image image

In the real world they wouldn’t have a gap in between, this is just to represent that they are separate grids in a map cluster.

When loading a world map you simply specify the width and height of the map in world coordinates, pixels for example, the cell size to split the world into again in world coordinates and if you have a large world you can decide to create a cluster by specifying the rows and columns to split the bigger world into. In this example that would look something like this.

World.SetupMap(1280,1280,160,2,2);

You can also load a world map by loading from a texture. In the current implementation it will assume 1 pixel of the image to be 1 GridCell. Here is a blown up example of one of the demos in the source code.

image

Brains will set any pixel that is black, to be a blocked type of GridCell, and any other colour to be an empty GridCell. The red and green pixels are loaded and annotated on the grid for your use but are not used internally in the engine. This makes it super easy to knock up a quick map to test out.

The Agent

A Brains A.I world also contains a list of Agent types. This type is used to provide autonomous behaviors to your game. An Agent stores some simple positioning properties such as Position, Radius and the Cells the Agent is currently in. It also stores the desired orientation and the desired position of an Agent for use with a Locomotion controller.

An Agent can store a set of feelers which can be used by your behaviors to poke data around the world.

The last defining feature of an Agent is it’s RootBehavior property. This is an IBehavior type which can be any type of behavior built into Brains, or your own custom implementation.

You can inherit from the Agent type to give you that extra flexibility when creating your autonomous characters.

Locomotion Controller

The Locomotion Controller is what controls the movement of an Agent. This is isolated from the Agent so that you can extend and implement the default implementation to get your characters moving how you want them to. There are 2 types of LocomotionController implemented in Brains. The basic movement controller which moves the agent from its current position to its desired position, and rotates it to face the desired rotation. The other Locomotion Controller is the LocomotionSteering which will allow you to make use of the famous Steering Behaviors For Autonomous Characters by Craig Reynolds. My version isn’t quite finished yet as I’m working on a better group design but the basic steering behaviors are working at the moment.

Behaviors

Brains contains some built in behaviors to form the basis of any combination of behaviors you may ever need to build. You can of course ignore these and implement your own.

With the Brains building blocks you can quickly build very complex behaviour trees without writing a ton of spaghetti code.

A Behavior Tree is made up of smaller blocks of hierarchical logic and built to recursively go down the tree until it finds a behavior to run. A simple representation of a Behavior Tree can be shown like this.

image

The circles represent a behavior and the lines show how the behavior breaks down into active actions an Agent may take based on decisions further up the tree. The Behavior tree is a much larger the subject than the scope of this post though so I will brush over the behavior building blocks built right into Brains.

Sequence Behavior

The Sequence Behavior has a set of sub behaviors which will run the first item in the list until it is successful, it will then move onto the next behavior in it’s sub behaviours in sequence. If a behavior fails it will fail the whole sequence.

Selector Behavior

The Selector Behavior also has a set of sub behaviors which it will run in sequence until it finds a success and then complete as a success itself.

Random Behavior

This Behavior randomly selects one of its child behaviors to run.

ParallelBehavior

This is a very primitive implementation of a Behavior which will run multiple behaviors at the same time. This raises a lot of complications with access to current data so will currently prove troublesome if the parallel is not a simple one.

Condition Behavior

Used to provide conditions before running other sub behaviors

Task Behavior

This is the behavior which would contain your A.I logic code. You would generally inherit from this to provide the specific game A.I logic.

Combining these set of components with your own and your imagination you can create extremely complex A.I decision making agents with great ease. With the added bonus of a Behavior Tree designer provided with the source code it’s even easier to let you just put on your game d

esigner hat or give the ability to a game designer to create a better game A.I

Brains also contains a few Task Behaviors for pathfinding around the world. You can also extend upon these to provide more flexible pathfinding.

They are:

Find Path Behavior

Finds a path from 1 GridCell to another.

Follow Path Behavior

Follows a provided path.

GoTo Behavior

This behavior combines the FindPath and FollowPath behaviors.

FollowRouteBehavior

This Behavior takes a series of GridCells. It will pathfind from one GridCell to the next and cycle once it’s complete. This makes use of the GoTo Behavior.

 

That’s a brief roundup of what Brains has to offer. It’s still unfinished and will continue to get development done to it. I want to tidy up some of the API exposure I’m not happy about yet (a few dirty hacks) and then I’ll post the source code for you to have a play with and give me some feedback.

Credits

The majority of my A.I reading has been from the AIGameDev web site. I’ve learned so much from there, I highly recommend it.

Some other helpful sites are of course the XNA Creators Club Online

A few other XNA A.I related projects have also been a great source of inspiration. Most notably Simple AI Engine for XNA and SharpSteer

XBox Live Community Games Listings

Posted by – April 27, 2009

A community created (Nick Gravelyn)  website has existed for some time which set out to emulate the functionality of the Xbox Marketplace but until very recently, it kind of sucked to look at. The information was there, but it was a fairly dull and average affair. But now, wow. Take a look for yourself. It’s almost like a direct copy of the Xbox Marketplace but it has 2 major benefits. It’s not slow, so you can go to it today, and read it today, and the other is user ratings. Go check it out for yourself, oh a third thing, the Box Art Collage is pretty sweet too, oh, and Random Game, i could go on but here’s the link. I’m going to find some new games to play :)

http://xblcg.info/

Congratulations to Nick Gravelyn & Scott Wendt & Björn Graf for getting this out without too much of a hiccup, I can see why Nick was so excited to get it out now. Great work with the new site.

xblcginfo

A Pinball Prototype

Posted by – April 24, 2009

Last night I set myself and a friend a challenge. Make a game in 1 night. We’ve done it before with Rock Paper Scissors Live. This time we failed, miserably. It’s not a functional game by any stretch of the imagination, however it is a cool little prototype.

2D Pinball was the genre we chose, so I created a new IceCream project and off I went. Using the Farseer integration it meant I had something up and running in no time, but it was proving difficult and time consuming to get the physics settings to feel like a pinball game. IceCream support for Farseer isnt quite complete yet, so there was quite a bit of code to write surrounding Springs and Joints. After some quick tweakage after arriving home I’ve got it to feel much better and much more like a pinball game. Here’s what it looks like now. I wonder if I’ll come back to this project and turn it into a game :) could be fun.

pinball

IceCream Release (Update)

Posted by – April 20, 2009

After finally releasing a release of IceCream early this morning which was probably not my wisest move as I was rushing and it showed in the release. Firstly I just messed up but secondly there were a couple of bugs I’ve been coping with that I should not have inflicted on anyone who tried it out. These were when you tried to open a project file and it couldnt find the scene file or no scene file was to be opened, the loading progress screen would stay alive and look like the app had hung. It didn’t, you just close the progress window and it’s ok to use. The second bug was deeper, when you open a project while already having a different project open, it would die a horrible death. I’ve been working hard on SBARG so it’s been a single project for me for some time. Both these bugs are now fixed in this release, along with an appropriate version number along with being compiled in Release mode so that should eliminate any debug performance issues.

You can grab the latest download of IceCream release here.

Again, please feel free to leave feedback, suggestions, comments or if you want some help email me at conkerjo at hotmail dot co dot uk.

SBARG – What is it?

Posted by – September 13, 2008

SBARG is a 2D RTS Game, in its basic form you might call it a “tower defense” style game. I think im going to invent a new genre right here and now called Turret Attack Game. So SBARG is a Turret Attack Game where you play as a robot who has to help Dr Strobo conduct his all important research. Your part in all of this madness is to protect Dr Strobo’s research pod where he resides from the destructive Weed Monsters. You do this by planting Pods in the world which attack and destroy the enemies. Enemies have different behaviours so different pods are required to counter this. The enemies also gain in strength and wit, upgrading pods enables you to increase your protection for Dr Strobo. You must use strategy to decide where to plant your pods because losing pods to Weed Monster attacks can be costly and ultimatly end in Dr Strobo’s demise.

I decided early on that SBARG should be as free as possible, so there is no grid to restrict your placement of pods in the world, and there are larger worlds which enable you to fly around and have even more freedom over placement. Some enemies will be very aware of its surroundings and dangers imposed and try to avoid attack before reaching its ultimate goal. Other enemies will not be so cautious or be aggressive by nature. This makes for very flexible gameplay and it’s very easy for one experience of the game to be very different to another.

SBARG is developed using the XNA Framework by myself and a friend who has produced the artwork for the game. It’s first target audience will be the judges for the Dream Build Play competition and after the game is complete it will be released to millions of XBOX users, which will be just an amazing feeling once it’s released.

Here is a tiny snippet of gameplay in screenshot form. There will be video footage soon of the game in action.

SBARG

SBARG

My first post of a new blog

Posted by – September 13, 2008

Here is my new home for me to talk about my project’s i’m working on.

First post so i’ll keep it short.

I will probably be talking about my game SBARG which is going to be entered in the DBP competition which is coming up very shortly. It’s a serious entry which i hope catches the attention of the judges enough to get some publicity for it, and because it’s almost complete feature wise i’ll be talking it up to try and get you interested in the game pending its full public release.

The picture you see in the title of the blog is Dr Strobo. He is an interesting character and i’ll tell you all about him in a future post.