Thursday 8 March 2012

Text revisited

Three months ago I described the class BTDText I created for Bug Tunnel Defense to replace the built-in TextField class. I used it again today to add some progress text to my game, and learned a couple of things in the process.


First I had to find out how to import fonts in Flex. For this I used the excellent guide here, which uses Flash CS but still means compilation is done by Flex. At the end of repeating those steps I had a font imported and working in game.


I next added a TextField/BTDText which is designed both to be easy to use and efficient, with options enabled so the bitmap is cached and the text cannot be selected. It had no event listeners and the container class also had cacheAsBitmap set so it would not update unless needed.


But despite all this, on adding some text I started seeing a slight performance hiccup, with dropped frames every second or so, on one of my test platforms (I use two browsers with two different versions of Flash Plugin to test as I work).


So I removed the text and replaced it with a BitmapData generated from the text. The hiccup vanished and the frame rate was back to normal. As this worked so well, and as I'm happy to have all my graphics as Bitmaps and BitmapData, I may add this into the BTDText class so it instead extends a BitmapData and draws to it on update.


The code I use is as follows. The Matrix matPercent is pre-calculated to adjust the baseline, while the BitmapData has already been added and is just being updated



public function SetPercent(fFrac:Number):void {
var iMille:int = fFrac * 1000;
var iPC:int = iMille / 10;
var iFrac:int = iMille % 10;
tfPercent.text = String(iPC) + "." + String(iFrac) + "%";
datPercent.fillRect(datPercent.rect, 0);
datPercent.draw(tfPercent, matPercent);
}

The other advantage of doing it this way is with the the final result a BitmapData all the effects applicable to a BitmapData can be applied to the text, even as it's drawn with the optional parameters of BitmapData draw(), generating a BitmapData that costs no more to render.

This would not work with editable text, and would probably be slower with text that's updated every frame. But for most game text it should provide a reliable performance boost, without the effort and extra file size associated with pre-rendering all text into loaded bitmaps.

No comments:

Post a Comment