March 2011 Entries
Preparing Myself For XNA and VB

For anybody who might have missed the news, XNA is coming to Visual Basic. I’ll admit that my first reaction was to groan and grumble and mumble. But this is actually a very good thing. While nothing’s ever certain, the fact that Microsoft has spent time making Visual Basic a supported language in XNA Game Studio is a further sign of Microsoft’s long-term commitment to XNA. (Note that VB.NET with XNA is not an immediately available thing; it’s still a few months off as the original blog post notes). And, as others pointed out, XNA has its roots in Managed DirectX (MDX), which was originally a VB.NET effort. So it’s only right and proper that XNA + Visual Basic will finally be a supported scenario. And devs who spend their days toiling away writing LOB apps in VB.NET deserve the same opportunity to spend their nights and weekends making their dreams come alive that those of us who are fluent in C# already have; it’s all CIL in the end.

So I welcome my VB coding .NET brethren and sistren (which should be a word) to XNA and shall do my best to help them just as I’ve helped others with XNA + C#. Of course when I first read the news I knew next-to-nothing about Visual Basic. And that’s what this post is actually about.

For those of you, like me, who have never done much of anything with VB, there are quite a few resources to help you translate between C# and VB. A great starting point is the MSDN Language Equivalents pages.

If you are simply looking to see what C#’s != is in VB, you can go there, click on the “Operators Compared in Various Languages” link, and see that it’s <>.

Sometimes, though, certain things just don’t exist. For example, VB, not having a C origin, doesn’t contain a sizeof operator. Nor does it have any prefix or postfix increments/decrements.

It does have other things that C# does not have, of course. Static local variables, for instance, simply don’t exist in C#. And there are certain names of things in VB that, to me at least, make more sense than the C# equivalent. VB’s MustOverride vs. C#’s abstract is an example of that.

Something that’s likely to drive me a bit crazy is VB’s case insensitive variable names. The (to me) common C# pattern of “private int someValue; public int SomeValue { get { return someValue; } set { someValue = value; } }” for properties and explicit fields simply won’t work in VB. To the extent that they allow mixed-language assemblies (something we’ll find out about later), at least some C# code will be in for some refactoring in order to make things accessible in VB. That’s all for the future still.

In the end, the most important thing I think I have to do is to not treat VB like it’s C# with a funny syntax. While the Language Equivalents reference I linked to above has been (and will continue to be) very helpful for getting an initial idea about what a particular block of VB code does, VB is a different language, not just a different syntax. When I left programming a decade ago, I was still treating C++ as C with objects (and I had tried my best to avoid the “with objects” part since I found the syntax ugly and confusing, especially when coupled with Hungarian notation). When I came back in to programming again, I initially started working with C for hobbyist stuff. I then found XNA and made the effort to learn C#. Of course I tried to treat C# as C with objects and that led to some spectacularly bad code (god objects, rampant abuse of static to recreate globals, etc.). I did eventually learn to appreciate objects and have improved quite a bit since then (though I do still have a tendency towards god objects that I have to actively suppress at times). I think that a lot of that is due to my personal preference for C#’s object orientation syntax over C++’s.

My goal with VB is not to make the same kind of mistake that I did with C#, i.e. not try to treat it as being a bizarro version of a language I already know. To that end I already have one print VB book and will doubtless be getting one or two more. I also have bookmarked the Visual Basic Programming Guide and the Visual Basic Language Reference. I’m going to spend some time recreating (not simply rewriting) certain apps and utilities that I’ve made in C# in the past in VB. And also spend a lot of time reading and studying existing VB projects to figure out what they are doing and how they are doing it both to try to recognize common VB constructs and patterns and also to internalize the keywords and other language syntax elements until I feel fairly confident in being able to write out working, performant VB code without the aid of a compiler or even Intellisense (something I can do reasonably well with C#).

It’s a long road and I don’t know how far along it I’ll be when XNA + VB arrives, but it should be an interesting journey regardless. It’s kind of exciting to learn a new language and it’s nice to have an impetus to do so. It’s something else to add to my mental toolkit and it should help make me a better programmer overall. And it’ll be very exciting to engage with a whole new wave of programmers, to help them understand XNA and solve any problems they might have encounter, and to see all the games they create. It will be an even busier Spring than I had originally imagined, but it will be an exciting one too!

Posted On Thursday, March 31, 2011 5:55 PM | Comments (1)
Drag and Drop in a Windows XNA Game

XNA Games in Windows are hosted within a Windows Forms Form. This allows you access to many special Windows-only features, such as drag and drop, provided that you know the right code to put in to get access to that form.

Someone on the App Hub forums had asked earlier today about how to enable drag and drop for a Windows-only XNA game. Since it sounded like a neat thing to learn how to do, I coded up a quick sample to display it. As always, the code is heavily commented so that it should be easy to follow along with. It’s licensed for use under the terms of the Microsoft Public License.

A few key notes. First, note that in the Program.cs file (where the static Main method that marks the entry point for the game is), I had to add an STAThreadAttribute to the Main method, since drag and drop requires the COM single threaded apartment threading model. I’m unaware of any negative repercussions that might have for an ordinary game (or editor or whatever you decide to build), but I wanted to note that since I doubt most people ever look at Program.cs. Also, I had to add a reference to System.Windows.Forms to the game project’s References in Solution Explorer.

The game will accept a drag and drop of most text (note that for reasons I have never been able to divine, you cannot drag and drop text from IE into anything other than IE – this is likely a by-product of a security thing, but I just don’t know). It will also accept a drag and drop of an image file! It only accepts either as a copy, not as a move, so there shouldn’t be any problems with that. I only implemented the bare minimum of error mitigation to prevent crashes. I did not implement proper error handling and the comments in the code reflect that. Drag and drop is enabled within the Initialize method of the Game1 class and event handlers for it are set there. If you drag text (e.g. from Word or WordPad), it will display the text (I enabled the DefaultCharacter in the SpriteFont to prevent crashes in case a particular character doesn’t exist in the font). If you drag and drop a file, it will attempt to load it as a texture and display it underneath where any text would be drawn. Note that only PNG, JPG, and GIF files will work and then only if the image’s dimensions are no greater than 2048x2048 (I switched the game to the Reach graphics profile in the game’s properties to enable as many people as possible to use it without needing to jump through that hoop).

Ok, without further rambling, here it is: .

For an example of Windows Forms drag and drop, see the sample code here: .

For a listing of the possible data formats the drag and drop allows, see: . You may need to search the internet a bit to figure out how some of them work (I had to do so to figure out that the FileDrop format returns a string array, for example).

Posted On Sunday, March 27, 2011 2:05 PM | Comments (1)
Musings on the Possible Future of Zune (Hardware)

For the past few weeks now there’s been a persistent “Zune is dead!” rumor. There was one a few months ago as well speculating about the name itself. The most recent one focuses on the hardware. It’s been “we have nothing to announce”-ed by Microsoft, which is Microsoft code for… having nothing to announce. As tech companies go, Microsoft doesn’t really go in for the whole rumor mill thing. The merits of that policy is a different discussion.

I don’t have any insider knowledge. I don’t know anyone at Microsoft beyond the occasional twitter conversation and exchange on the App Hub forums. So, this is quite simply just my own musings and thoughts on the recent to-do.

For a number of years now, Microsoft has made Zune hardware. I’ve never owned a Zune (nor any other portable music player since a portable CD I had for a car that only had a tape deck more than a decade ago) but I’ve heard generally good things about them. But the rumors are that Microsoft may not be making another Zune device. This has been covered as being doom and gloom with all the usual stereotypes about Microsoft. But I see it as a potentially good thing, assuming it’s true.

Last fall Microsoft launched Windows Phone 7. If you haven’t yet used one, let me assure you that it’s a really nice platform. Everyone I’ve shown my WP7 to has been impressed and most have said, in one way or another, that the ads just don’t do it justice. (I don’t know that it’s possible to really capture it’s elegance in an ad). I expect it to continue to grow as more people come in contact with it and as their existing phone contracts expire. Smart phones are expensive. Most people I know that have one have gotten it as part of a new 1 or 2 year phone service agreement and so until their existing contracts expire it’s unlikely they’d spend the $500+ to buy one outright. I expect that’s true for most people in general. I also expect the recent addition of Sprint and the future addition of Verizon to add to adoption rates. (I know a number of people who have been/still are waiting for Sprint/Verizon WP7 phones).

Nonetheless, it’s a simple truth that people who already have other smartphones have a lot of time and money invested in their current phone platform in the form of apps, games, etc. There are also quite a few people who have phones through their job such that the choice of phone is out of their hands. So not everyone who would be interested in the Windows Phone 7 platform would be willing or able to get a WP7 phone.

What does that have to do with Zune hardware? Well, WP7 (as a platform) is the next logical Zune device. It interfaces with the Zune software. It stores and plays music, podcasts, and movies. And it integrates very well with a Zune Pass. Many great consumer hardware companies are shipping WP7 devices and more companies are on the horizon. The phone part of Windows Phone 7 is great, but it’s just one part of the platform. There’s no technical reason why someone like Samsung couldn’t strip the phone hardware out of the Focus and sell it as a competitor to the iPod Touch as-is (let alone with a few sweet additions).

I know a lot of people with “dumb” phones who have an iPod Touch. So why shouldn’t there be a WP7-based competitor? Indeed, why shouldn’t there be multiple WP7-based competitors from different manufacturers each meeting the base WP7 hardware specs and providing additional goodies on top of that to attract consumers? That would open up the platform to people who are interested in WP7 for Xbox LIVE games, Office on the go, and the many other great features of the WP7 platform but who already have another smartphone that they aren’t able to switch from for one reason or another. Stripping out the phone hardware and adding in an A/V out to play music and videos through a home entertainment center would make for a really great WP7 device, for example.

Were that to come to pass, it simply wouldn’t make sense for Microsoft to make new Zune hardware. All of those devices would be Zune hardware, after all, just like WP7 phones are currently. And it’d be hard to convince consumer hardware companies to make them if the company making the OS that powers them were making competing hardware. So to me, the rumors of no more Microsoft-made Zune hardware would fit perfectly with a strategy of launching a wave of WP7-based iPod Touch competitors at some point in the future (e.g. Holiday 2011 or Summer 2012).

Anyway, just my thoughts on one thing these rumors could mean. If my speculation turns out to be right, I doubt we’d hear anything about it before Autumn anyway. I’ll be keeping my fingers crossed, though, because I think that’d be a great future development for Zune and the WP7 platform!

Posted On Friday, March 25, 2011 3:53 PM | Comments (1)
Sprite Padding Using Guides in Gimp

Lately I’ve been doing a lot of drawing. A lot of it has been creating sprite animations for XNA projects. From many years of using it, I work primarily with Gimp. Some aspects of it frustrate me (mostly its awkward window management in Windows), but it suits my purposes well enough and lets me do things that other free solutions don’t.

One thing I learned quite some time ago was that when including multiple items in a single texture (i.e a sprite sheet), you want to have some separation between each item to avoid bleeding between items if you do any in-game scaling. Something like 2-4 pixels should do the trick.

Unfortunately, spacing these things out properly can get very annoying very quickly. Gimp provides the ability to display a grid, but no ability to add padding between cells. It also provides the ability to add guides. Guides are horizontal or vertical lines that you can snap to when selecting things (if desired – you can toggle that behavior on and off in the View menu) and which appear and are saved in an XCF file (Gimp’s native file format) but which don’t affect your PNG file (or whatever format you save textures as for importing into your game). Unfortunately, adding guides one-by-one gets old fast.

So to save myself five minutes of work the other day, I spent two and a half hours learning Scheme to the point where I could write a plugin to automatically add guides for me. Yes, I could have learned Python, but I know slightly more Scheme (a tiny bit) than Python (nothing beyond that it uses spacing to delineate code blocks) and the Scheme interpreter is bundled with Gimp such that nobody needs install anything extra to use a Scheme-based plugin.

Anyway, I created this plugin. You can download it here: provided you agree to the terms of the Microsoft Public License. To use it, you need to put it into Gimp’s scripts directory, which is normally “.gimp-2.6\scripts\” in your home directory (e.g. “C:\Users\username\” on Vista/7 or “C:\Documents and Settings\username\” on XP). If you’re using Vista or 7 you may have to unblock it.

You’ll then find when you start up Gimp and open an image, that in the “Image->Guides” menu there’s now an “Add Sprite Guides…” menu item. Click that (and find the window that pops up, often under the image windows) and you will be presented with a dialog window with four entries: Sprite Width; Sprite Width Padding; Sprite Height; and Sprite Height Padding. The default values are 64, 2, 64, and 2, respectively (you can change the defaults if you want by editing the .SCM file). Replace the values with the width of your sprite frame in pixels (e.g. 96), the height of your sprite frame in pixels (e.g. 128), and the padding you want between each sprite (I have 2 for width and height, but you can use any positive value and they do not need to be the same, e.g. you could have 3 for width and 5 for height if you wanted). Click “OK” and guides will be created for you starting at width, then width + padding then (width + padding) + width then… . Gimp already has a built-in “Remove All Guides” under “Image->Guides” so if you want to get rid of them (or swap them out for a different size), you can simply use that and they’re gone.

Anyway, I find them handy. Perhaps you will too! You’ll need to make sure to bake the padding in to calculating the positions of your source rectangles, but the math to do that is pretty easy.

n.b. The code itself is not pretty and would probably make a real Scheme developer shudder, but it works. I wound up learning more after I got it working such that I would write it differently (and more correctly) if I did it again, but I don’t have time to make a small piece of working code that’s not part of a larger project work more correctly. Still, Scheme was more enjoyable than I had remembered it being. The older I get, the more interesting functional programming becomes to me. Need to find some time to look at F# in more depth one of these days.

Posted On Thursday, March 24, 2011 3:43 AM | Comments (2)
AccelerometerInput XNA GameComponent

Bad accelerometer controls kill otherwise good games. I decided to try to do something about it. So I create an XNA GameComponent called AccelerometerInput. It’s still a beta project but you are welcome to try it, use it, modify it, etc. I’m releasing under the terms of the Microsoft Public License.

Important info:

First, it only supports tilt-style controls currently. I have not implemented motion-style controls yet (and make no promises as to when I might find time to do so).

Second, I commented it heavily so that you can (hopefully) understand what it is doing. Please read the comments and examine the sample game for a usage overview. There are configurable parameters which I encourage you to make use of (both by modifying the default values where your testing shows it to be appropriate and also by implementing a calibration mechanism in your game that lets the user adjust those configurable values based on his or her own circumstances).

Third, even with this code, accelerometer controls are still a fairly advanced topic area; you will likely find nothing but disappointment if you simply plunk this into some project without testing it on a device (or preferably on several devices).

Fourth, if you do try this code and find that something doesn’t work as expected on your phone, please let me know as I want to improve it and can only do so with your help. Let me know what phone model it is, what you tried doing, what you expected, and what result you had instead. I may or may not be able to incorporate it into the code, but I can let others know at the very least so that they can make appropriate modifications to their games (I’m hopeful that all phones are reasonably similar in their workings and require, at most, a slight calibration change, but I simply don’t know).

Fifth, although I’ll do my best to answer any questions you may have about it, I’m very busy with a number of things currently so it might take a little while. Please look through the code and examine the comments and sample game first before asking any questions. It’s likely that the answer is in there. If not, or if you just aren’t really sure, ask away.

Sixth, there are differences between a portrait-mode game and a landscape mode game (specifically in the appropriate default tilt adjustment for toward the user/away from the user calculations). This is documented and the default is set for landscape. If you use this for a portrait game, make the appropriate change (look for the TODO: comment in AccelerometerInput.cs).

Seventh, no provision whatsoever is made for disabling screen locking. It is up to you to implement that and to take appropriate measures to detect when the user has been idle for too long and timeout the game. That code is very game-specific. If you have questions about such matters, consult the relevant MSDN documentation and, if you still have questions, visit the App Hub forums and ask there. I answer questions there a lot and so I may even stumble across your question and answer it. But that’s a much better forum than the comments section here for questions of that sort so I would appreciate it if you asked idle detection-related questions there (or on some other suitable site that you may be more familiar and comfortable with).

Eighth, this is an XNA GameComponent intended for XNA-based games on WP7. A sufficiently knowledgeable Silverlight developer should have no problem adapting it for use in a Silverlight game or app. I may create a Silverlight version at some point myself. Right now I do not have the time, unfortunately.

Ok. Without further ado:

Have a great St. Patrick’s Day!

Posted On Thursday, March 17, 2011 11:02 AM | Comments (0)
Tips for XNA WP7 Developers

There are several things any XNA developer should know/consider when coming to the Windows Phone 7 platform. This post assumes you are familiar with the XNA Framework and with the changes between XNA 3.1 and XNA 4.0. It’s not exhaustive; it’s simply a list of things I’ve gathered over time. I may come back and add to it over time, and I’m happy to add anything anyone else has experienced or learned as well.


· The screen is either 800x480 or 480x800.

· But you aren’t required to use only those resolutions.

· The hardware scaler on the phone will scale up from 240x240.

· One dimension will be capped at 800 and the other at 480; which depends on your code, but you cannot have, e.g., an 800x600 back buffer – that will be created as 800x480.

· The hardware scaler will not normally change aspect ratio, though, so no unintended stretching.

· Any dimension (width, height, or both) below 240 will be adjusted to 240 (without any aspect ratio adjustment such that, e.g. 200x240 will be treated as 240x240).

· Dimensions below 240 will be honored in terms of calculating whether to use portrait or landscape.

· If dimensions are exactly equal or if height is greater than width then game will be in portrait.

· If width is greater than height, the game will be in landscape.

· Landscape games will automatically flip if the user turns the phone 180°; no code required.

· Default landscape is top = left. In other words a user holding a phone who starts a landscape game will see the first image presented so that the “top” of the screen is along the right edge of his/her phone, such that the natural behavior would be to turn the phone 90° so that the top of the phone will be held in the user’s left hand and the bottom would be held in the user’s right hand.

· The status bar (where the clock, battery power, etc., are found) is hidden when the Game-derived class sets GraphicsDeviceManager.IsFullScreen = true. It is shown when IsFullScreen = false. The default value is false (i.e. the status bar is shown).

· You should have a good reason for hiding the status bar. Users find it helpful to know what time it is, how much charge their battery has left, and whether or not their phone is in service range. This is especially true for casual games that you expect someone to play for a few minutes at a time, e.g. while waiting for some event to start, for a phone call to come in, or for a train, bus, or subway to arrive.

· In portrait mode, the status bar occupies 32 pixels of space. This means that a game with a back buffer of 480x800 will be scaled down to occupy approximately 461x768 screen pixels. Setting the back buffer to 480x768 (or some resolution with the same 0.625 aspect ratio) will avoid this scaling.

· In landscape mode, the status bar occupies 72 pixels of space. This means that a game with a back buffer of 800x480 will be scaled down to occupy approximately 728x437 screen pixels. Setting the back buffer to 728x480 (or some resolution with the same 1.51666667 aspect ratio) will avoid this scaling.


· Touch input is scaled with screen size.

· So if your back buffer is 600x360, a tap in the bottom right corner will come in as (599,359). You don’t need to do anything special to get this automatic scaling of touch behavior.

· If you do not use full area of the screen, any touch input outside the area you use will still register as a touch input. For example, if you set a portrait resolution of 240x240, it would be scaled up to occupy a 480x480 area, centered in the screen. If you touch anywhere above this area, you will get a touch input of (X,0) where X is a number from 0 to 239 (in accordance with your 240 pixel wide back buffer). Any touch below this area will give a touch input of (X,239).

· If you keep the status bar visible, touches within its area will not be passed to your game.

· In general, a screen measurement is the diagonal. So a 3.5” screen is 3.5” long from the bottom right corner to the top left corner. With an aspect ratio of 0.6 (480/800 = 0.6), this means that a phone with a 3.5” screen is only approximately 1.8” wide by 3” tall. So there are approximately 267 pixels in an inch on a 3.5” screen.

· Again, this time in metric! 3.5 inches is approximately 8.89 cm. So an 8.89 cm screen is 8.89 cm long from the bottom right corner to the top left corner. With an aspect ratio of 0.6, this means that a phone with an 8.89 cm screen is only approximately 4.57 cm wide by 7.62 cm tall. So there are approximately 105 pixels in a centimeter on an 8.89 cm screen.

· Think about the size of your finger tip. If you do not have large hands, think about the size of the fingertip of someone with large hands. Consider that when you are sizing your touch input. Especially consider that when you are spacing two touch targets near one another. You need to judge it for yourself, but items that are next to each other and are each 100x100 should be fine when it comes to selecting items individually. Smaller targets than that are ok provided that you leave space between them.

· You want your users to have a pleasant experience. Making touch controls too small or too close to one another will make them nervous about whether they will touch the right target. Take this into account when you plan out your game initially. If possible, do some quick size mockups on an actual phone using colored rectangles that you position and size where you plan to have your game controls. Adjust as necessary.

· People do not have transparent hands! Nor are their hands the size of a mouse pointer icon. Consider leaving a dedicated space for input rather than forcing the user to cover up to one-third of the screen with a finger just to play the game.

· Another benefit of designing your controls to use a dedicated area is that you’re less likely to have players moving their finger(s) so frantically that they accidentally hit the back button, start button, or search button (many phones have one or more of these on the screen itself – it’s easy to hit one by accident and really annoying if you hit, e.g., the search button and then quickly tap back only to find out that the game didn’t save your progress such that you just wasted all the time you spent playing).

· People do not like doing somersaults in order to move something forward with accelerometer-based controls. Test your accelerometer-based controls extensively and get a lot of feedback. Very well-known games from noted publishers have created really bad accelerometer controls and been virtually unplayable as a result. Also be wary of exceptions and other possible failures that the documentation warns about.

· When done properly, the accelerometer can add a nice touch to your game (see, e.g. ilomilo where the accelerometer was used to move the background; it added a nice touch without frustrating the user; I also think CarniVale does direct accelerometer controls very well). However, if done poorly, it will make your game an abomination unto the Marketplace. Days, weeks, perhaps even months of development time that you will never get back. I won’t name names; you can search the marketplace for games with terrible reviews and you’ll find them.


· The maximum frame rate is 30 frames per second. This was set as a compromise between battery life and quality.

· At least one model of phone is known to have a screen refresh rate that is between 59 and 60 hertz. Because of this, using a fixed time step with a target frame rate of 30 will cause a slight internal delay to build up as the framework is forced to wait slightly for the next refresh. Eventually the delay will get to the point where a draw is skipped in order to recover from the delay. (See Nick's comment below for clarification.)

· To deal with that delay, you can either stay with a fixed time step and set the frame rate slightly lower or else you can go to a variable time step and make sure to adjust all of your update data (e.g. player movement distance) to take into account the elapsed time from the last update. A variable time step makes your update logic slightly more complicated but will avoid frame skips entirely.

· Currently there are no custom shaders. This might change in the future (there is no hardware limitation preventing it; it simply wasn’t a feature that could be implemented in the time available before launch).

· There are five built-in shaders. You can create a lot of nice effects with the built-in shaders.

· There is more power on the CPU than there is on the GPU so things you might typically off-load to the GPU will instead make sense to do on the CPU side.

· This is a phone. It is not a PC. It is not an Xbox 360. The emulator runs on a PC and uses the full power of your PC. It is very good for testing your code for bugs and doing early prototyping and layout. You should not use it to measure performance. Use actual phone hardware instead.

· There are many phone models, each of which has slightly different performance levels for I/O, screen blitting, CPU performance, etc. Do not take your game right to the performance limit on your phone since for some other phones you might be crossing their limits and leaving players with a bad experience. Leave a cushion to account for hardware differences.

· Smaller screened phones will have slightly more dots per inch (dpi). Larger screened phones will have slightly less. Either way, the dpi will be much higher than the typical 96 found on most computer screens. Make sure that whoever is doing art for your game takes this into account.

· Screens are only required to have 16 bit color (65,536 colors). This is common among smart phones. Using gradients on a 16 bit display can produce an ugly artifact known as banding. Banding is when, rather than a smooth transition from one color to another, you instead see distinct lines. Be careful to avoid this when possible. Banding can be avoided through careful art creation. Its effects can be minimized and even unnoticeable when the texture in question is always moving. You should be careful not to rely on “looks good on my phone” since some phones do have 32-bit displays and thus you’ll find yourself wondering why you’re getting bad reviews that complain about the graphics. Avoid gradients; if you can’t, make sure they are 16-bit safe.


· Never rely on sounds as your sole signal to the player that something is happening in the game. They might have the sound off. They might be playing somewhere loud. Etc.

· You have to provide controls to disable sound & music. These should be separate.

· On at least one model of phone, the volume control API currently has no effect. Players can adjust sound with their hardware volume buttons, but in game selectors simply won’t work. As such, it may not be worth the effort of providing anything beyond on/off switches for sound and music.

· MediaPlayer.GameHasControl will return true when a game is hooked up to a PC running Zune. When Zune is running, any attempts to do anything (beyond check GameHasControl) with MediaPlayer will cause an exception to be thrown. If this exception is thrown, catch it and disable music. Exceptions take time to propagate; you don’t want one popping up in every single run of your game’s Update method.

· Remember that players can already be listening to music or using the FM radio. In this case GameHasControl will be false and you should handle this appropriately. You can, alternately, ask the player for permission to stop their current music and play your music instead, but the (current) requirement that you restore their music when done is very hard (if not impossible) to deal with.

· You can still play sound effects even when the game doesn’t have control of the music, but don’t think this is a backdoor to playing music. Your game will fail certification if your “sound effect” seems to be more like music in scope and length.

Posted On Thursday, March 10, 2011 10:03 PM | Comments (4)
CheckMemoryAllocationGame Sample

Many times I’ve found myself wondering how much GC memory some operation allocates. This is primarily in the context of XNA games due to the desire to avoid generating garbage and thus triggering a GC collection. Many times I’ve written simple programs to check allocations. I did it again recently.

It occurred to me that many XNA developers find themselves asking this question from time to time. So I cleaned up my sample and published it on my website. Feel free to download it and put it to use. It’s rather thoroughly commented. The location where you insert the code you wish to check is in the Update method found in Game1.cs. The default that I put in is a line of code that generates a new Guid using Guid.NewGuid (which, if you’re curious, does not create any heap allocations).

Read all of the comments in the Update method (at the very least) to make sure that your code is measured properly. It’s important to make sure that you meaningfully reference any thing you create after the second call to get the memory or else (in Release configuration at least) you will likely get incorrect results. Anyway, it should make sense when you read the comments and if not, feel free to post a comment here or ask me on Twitter.

You can find my utilities and code samples page here:

To download CheckMemoryAllocationGame’s source code directly:

(If you’re looking to do this outside of the context of an XNA game, the measurement code in the Update method can easily be adapted into, e.g., a C# Windows Console application. In the past I mostly did that, actually. But I didn’t feel like adding references to all the XNA assemblies this time and… anyway, if you want you can easily convert it to a console application. If there’s any demand for it, I’ll do it myself and update this post when I get a chance.)

Posted On Tuesday, March 1, 2011 11:30 AM | Comments (0)
Bob Taco Industries is an ISV focused on game and app development for Microsoft platforms headed up by Michael B. McLaughlin. Mike is a Microsoft Visual C++ MVP (previously an XNA/DirectX MVP from 2011-2013), a developer, a writer, a consultant, and a retired lawyer. If you're a developer who is just getting started, consider checking out the BTI website's section for developers for links to code samples and other helpful sites.
Tag Cloud