Game Object State Management in XNA

Vegas Building

Hmm. This sounds a bit deep for a Saturday blog post. I suppose it is, but I got asked a question at Mix 11 and I’ve been pondering it ever since then. The question was about some code like this:

class Cloud : CloudGame.ISprite
{
    public Texture2D CloudTexture;
    public Vector2 CloudPosition;
    public Vector2 CloudSpeed;
    public bool Burst = false;

    public void Draw(CloudGame game)
    {
        if (!Burst)
            game.spriteBatch.Draw(CloudTexture, 
                                                                       CloudPosition, 
                                                                       Color.White);
    }
   // rest of cloud code here
}

This is a tiny part of my “Cloud Bursting” game demo, where players touch clouds to burst them. The above code is the definition of the cloud itself. This has a texture, position, speed of movement and a Burst flag as properties.

Burst is how the cloud “knows” if the cloud has been burst. If the cloud is burst it is not drawn. At the start of the game all the clouds have the Burst flag set to false to indicate that they are still part of the game. As the player touches them the Burst flag is set true.

You see this in a lot of game play situations. Anywhere that things are “killed” they have to be able to remember whether they are still alive or not. The code above is simple and works well, at any instant a cloud is either burst or not. If it is burst (i.e. the Burst flag is true) plays no further part in the game and is not drawn.

However, this design gave rise to the question: “Why do we need to have a flag? Surely it would be more efficient to remove a ‘burst’ cloud from the list of things to be drawn?”

This is a very good question. To understand it you need to remember that in a game we will have many objects on the screen at any given time. To manage this the game contains a collection of some kind (usually a List). During Update and Draw the game works through the list acting on each item in it. If an item is removed from the list it will no longer be part of the game.  When the player bursts a cloud, rather than setting a flag you could just remove that cloud from the list of active game objects.

This approach has the advantage that it is more efficient. Instead of a cloud having to decide not to draw itself the game never tries to draw burst clouds at all.  However, it also adds complication. The game must now have a “master” list of clouds and an “active” list of clouds. At the start of a game the master cloud references are copied into the active list. This is to avoid the overheads of creating and destroying objects, something you really don’t want to be doing on a regular basis.

Furthermore, the time that is saved is probably not going to be that much use to us. If the game works fine with all the clouds visible (which it should do) then saving small amounts of processor time when some clouds are removed is not going to make that much difference to performance. In this situation it is the drawing of the objects that takes the time, not deciding whether or not to draw them.

The fundamental principle here is that you should go for simplicity first, then optimise when you discover you have a performance issue.  I like having the flags present, it makes for greater cohesion and easier debugging. I can look at any cloud and decide whether or not it should be drawn simply by inspecting the flag.  If the flag wasn’t there I’d have to check which lists held the cloud, and so on.

So, I go with internal flags, not lists, which is pretty much what I said at the time as I remember.

Some Mix Videos to Watch

Walk

If you weren’t at Mix and you want to watch the video of my session you can now view it here:

http://channel9.msdn.com/Events/MIX/MIX11/EXT06

You can get all the demo code that I talk about here:

/demos

This afternoon I was invited to take part in a Live Channel 9 session on video game design. Also on the stage was Brandon Foy, perhaps the coolest person I have ever met. He is the creator of an astonishing Windows Phone fan video that you can view on YouTube here:

http://www.youtube.com/windowsphone

Microsoft have said that if they get more that 200,000 views they will pay to put it out as a TV advertisement.  So, if you want to cost Microsoft some money, go take a look. Actually, it is a stunning piece of work and well worth 2 minutes of anyone’s time.

The video game session itself was great fun, as well as Brandon there was Nic Fillingham  from the XNA team and John Papa kept us all under control. For me the interesting thing was how much we all agreed on what is important in video game design. In a nutshell:

  • Figure out what your game is about and then protect this idea against all who would wish to “improve” it.
  • Get help with the graphics. Programmers think they can solve any problem with software. They probably can, but graphical design is not a problem as such. You really need someone with a good eye for that, and a coder is not guaranteed to be that person.
  • Put your game into the hands of people who can give you proper feedback. This doesn’t mean family or friends, this means those whose only reason the like the game is the game itself.
  • Design in the persistence features right at the start. A phone game will have to stop and start. When you make the game objects you need to figure out which bits must be saved and when. Adding this stuff right at the end of the development is really hard. If you have this stuff there all the time it means it will be properly tested when you send the game out.

After this I staggered back to the hotel to do some packing. My flight leaves at 7:15 am tomorrow. Lovely.

Mix 11 Keynote Windows Phone Fun

Scott Guthrie at the keynote
Scott Guthrie describing all the new goodies for Visual Studio and Windows Phone Mango.

Went to the Mix 11 keynote today. The new Windows Phone version, codenamed Mango and due for release later this year, looks very good. It seems as if they’ve worked through the wish list from the previous release and just about added everything.

Mango gives task switching, background processing (in a very well managed way), sockets, an on-board database, application powered Live Tile support and some lovely enhancements to the user interface. Furthermore, the emulator enhancements in Visual Studio will make it really easy to simulate the accelerometer and GPS system. And we will also be getting some impressive performance monitoring tools.

Applications will also now be able to use both Silverlight and XNA components in the same program, which will make creating game menus much easier. There was so much stuff I’ve probably forgotten something..

The tools will be available next month, the phones start being upgraded around autumn. This is great news for Windows Phone lovers like me, and anyone who fancies following the easiest path to mobile development that there is.

After the keynote I went for a wander.

Kinect Powered Lazyboy

This is a Kinect controlled LazyBoy recliner. Just move your hands in front of the sensor to move around and even recline the seat. Amazing.

Curious Cloud readings

Over at the Curious Cloud stand they are now getting readings from teams who have devices that are uploading sensor data to the cloud.

Mix 11 Windows Phone Booth Session

BoothAudience
I asked the audience to sit down and look at me as if I’d just said something amazing. They did a great job. Such good sports. I wasn’t intending to produce a panoramic shot, but the stitching seems to have worked quite well. The guy with the accordion is one of the few people out there who has actually bought a copy of Cheese Lander. Make of that what you will.

In the afternoon I got to do my phone session again, as stand-up. Went very well, I was determined to get someone on every seat watching me and by the end I kind of had.

For those of you who made it through to the end, especially the VB developer who went away with a copy of my book, thanks for being there, I’d have felt really silly if I’d just been presenting in front of nobody.

Next stop, Ask the Experts, starring me as an expert. How could that go wrong…..

Mix 11 XNA Madness

Room Left

This is the left hand side of the room. The right hand side were just as good looking. You can find that picture on Flickr, just click through to get there.

Just done my Mix 11 session. Great fun. Needed nerves of steel (or at least corrugated cardboard) when the video projector shut down just at the start. Fortunately the audience was super terrific. And most of them like cheese. Some great questions at the end.

You can find the slides for my session here.

I’ve made a brand new demos site with all the session demos for today, plus loads of other Windows Phone good stuff. You can find it all here:

/demos

I’ll keep this up to date with any new stuff I write, and move some other things in there that are presently hard to find.

If you want to see me go through any of the other demos, catch me at the Windows Phone Booth today at 2:00.

Rube Goldberg and the Micro Framework at Mix

Curious Cloud Poster

I’m going to try and watch the local news over the next few days. I’ll be looking for reports of folks performing strange contortions under street lights and near air conditioning vents. If I do see any, I’ll know what it is about though. They’ll be people taking part in the Rube Coldberg Curious Cloud Contest. The idea is simple enough. You get a magic device that responds to temperature, light and motion. By getting the right conditions of these you can get three lights on the device to come on. This makes you a winner.

It turns out that, with a bit of experimentation, anyone can get the lights to come on (particularly if they take a look at the C# code that powers this .NET Micro Framework based contraption). So the biggest prizes go to those who can make them come on in the most interesting way. Dressed as a chicken perhaps, or using a robot, or on the street. Or all three.

Curious Hardware

The hardware doing all this is pretty impressive. A netDuino board sits at the bottom, talking with a WIFI adapter and a sensor/display board. It captures readings from the sensors to an on-board memory card. When the device is able to detect a WIFI signal it will upload all the recent readings to the Cloud, where anyone can take a look. So, in a package around the size of a cigarette pack we have a .NET capable processor, sensors, data logging and wireless networking.

I got to have an early play with one of the kits, you can find my sensor readings here:

I’ve not found the magic values yet, but I reckon the fun is in the journey.

Colin Miller, of the .NET Micro Framework team, is dishing out complete kits to lucky Mix delegates who want to form a team and want to have a go. He will be on hand from tomorrow in the Connect Lounge (at Shorelines A) dishing out kits for you to play with.

Curious Cloud Box

The kits are beautifully presented, with all you need to get started, including a battery pack so you can take your sensors out and about.  You could even use a Windows Phone app to visualise your results.

Find out more at http://curiouscloudcontest.com when the competition opens tomorrow.

Vegas Shopping

Mandalay

If I ever have a business where I need some of the best sales people in the world I’m going to hire folks from the ‘states. Absolutely. I went shopping today and it experienced the full force sales experience stateside. People in the shops here really want you to have a good day. And they reckon the best kind of day is spent buying their stuff. I went down to one of the Vegas Outlet malls and was bowled over by the people there. In a very expensive kind of way.  I know that you can get good and bad service anywhere in the world, but out here it seems that good far outweighs the bad.

And I found out something new about Las Vegas since I was last here. They now have a Fry’s Electronics. And you can get there on the bus. Fry’s is a big brand across the ‘states. The have warehouse sized shops filled with everything, from individual electronic components up to full blown AV systems. I must have been in there for two hours looking at stuff.

The bus is the one that goes up and down the strip. Seven dollars buys you a day’s worth of travel and it is one of the greatest bargains in this town. The busses are frequent and shiny new.  And the bus station is ace.

Bus Station Panorama
I  call this one “Bus Station Panorama”

Bus Station Tiles
.. and this one is the tiles on the wall

I staggered back late afternoon with my purchases, and then headed out to meet some of the Windows Phone crew for a drink and a bite. Great fun, I met a couple of folks from Boston who’s names I’ve completely forgotten (although I do remember pretty much everything else) and I also met up with the chap who wrote the original version of Farseer. Since he is the man who made “Destruction Golf” possible, I shook him warmly by the hand..

I finally crashed into bed way later than I should have been up, but it it was a really good evening. The conference proper starts tomorrow. With around 20 hours or so of beauty sleep I should be fine…

Going Large at Mix 11 in Las Vegas

Mandalay Morning

One of my frequent refrains to students is that they should write a blog. Not because the world necessarily needs to know what they think, but because the exercise of writing a reasonable amount regularly is extremely good for you. It makes you more able to express yourself.

Some people go all out for physical fitness, which is fair enough I suppose. Having taken a long hard look at my body some years ago (those full length mirrors they put in hotel bathrooms don’t help at all) it dawned on me that it was very unlikely, even with a lot of keep fit, that I could ever make a living from my physique. However, writing did seem to offer possibilities. So I started blogging, and I’ve done so for quite a while now. Every now and then I try to stretch things a bit by forcing myself to write a lot more words than I normally do, and here we are.

While I’m in Vegas, and while I’m still waking up at one in the morning with a head full of cold and words in equal measure, I’m going to write some longer posts about the experience. But there will still be pictures.

I set off yesterday mid-morning, taking off from the ninth best airport in the world, which is just down the road from our house.  On the plane I ended up setting next to a fellow academic, which was nice, and so I was able to spend the time taking shop all the way to Schipol.

Things got even better when I was checking in for the next flight in my journey. One of the people on the check-in desk noticed that I was quite tall and offered to upgrade me to Business Class.  I really like Delta airlines. Last time I flew with them they picked me out and got me a seat with legroom, this time it was a whole new experience. The only problem really was with my attire. I dress for comfort when travelling, so I was in pair of worn jeans and a shirt I’m not that fond of. I didn’t actually resemble a hobo, but a straw hat and a banjo would not have looked out of place in my ensemble.  The lady upgrading me made this point as diplomatically as possible, and so I did tuck my shirt in..

Tips for travel from Rob: if you want to get upgraded it is probably  best to dress a bit smarter for your flight. The other folks in Business Class, who have paid a considerable premium for that status, might not appreciate someone sitting next to them who looks like they just climbed off a tractor. Having said that, I think I just about nailed the “eccentric millionaire” look.

As a consequence of my good fortune the flight to Detroit was excellent, with superb service, amazing food and a chair that you could tip up and down with a little control panel.

At Detroit I had to change planes, but before that I had to actually get into the country. The man at Homeland Security, having got my fingerprints and stuff, then asked some very searching questions about my trip. I told him I was giving a talk at Mix and he asked “Why you?”. I didn’t really have a good answer to this one, saying it was because I know lots of good jokes probably wouldn’t have impressed (and the point itself is debateable). Worst still he might then have asked me to make him laugh, which looked like it would have been tricky. In the end I murmured something like “Microsoft seem to like me” and he let me in.

I then had a Brief Encounter with my case, before handing it back into the system for the transfer to Vegas. In the wonderful Discworld novels one character has a magical trunk called “The Luggage” which follows him everywhere. My case is a bit like that, but in reverse.

I’d brought along my Kindle, which turns out to be an excellent travelling companion. I even managed to use the prototype web browser to check my email while waiting for my flight to be called. It worked fine apart from one tiny problem, which was that for my Outlook web mail it rendered the text as black on black background. But I did manage to buy a book while I was waiting, and then read pretty much all of it on the  way. The book was “An Unsuitable Job for a Woman” by PD James, a well written whodunnit with great descriptions of the characters and locations and a well constructed plot – although I did manage to figure out quite a bit of it. A clue, the person that looks evil sometimes is.

The flight out of Detroit was smooth enough,  but by now my head cold was really kicking in and I spent the whole time sniffling and sneezing my way over the USA.  I must apologise to the people who were forced to sit next to me, although I was relieved, in a perverse sort of way, when the chap on one side immediately produced sniffles and sneezes that put mine to shame. I now have a worrying vision of two transatlantic teams of cold germs ganging up and attacking my sinuses over the next few days. Oh well.

Once I got to Vegas my case did the usual trick of hiding at the back of the plane, so that it was absolutely the last one onto the carousel. I really think it doesn’t like me very much. Then I grabbed a cab to the hotel and crashed out for as long as I could, which turned out to be four hours. So I wandered round the room with the camera and a tripod taking pictures of stuff. I’ve seen them do this in CSI loads of times.

Mandalay Mini Bar
Tempting minibar

Stereo Sinks
Stereo sinks. I’m tempted to try washing a foot in each one at the same time, but I fear this may end badly.

Generous Prizes
Generous prizes for my session. All the way from the UK

Watch and RoomKey
Watch and Room Key

The Mandalay Bay hotel is enormous. The room numbers on each floor have three digits, because they have many hundreds of rooms on each level. My room is number 333, which is the same number as my office at Hull. Coincidence? I think so.

More later.