Thursday, 8 December 2011

My TextField class

This is a class I added to replace all instances of TextField in Bug Tunnel Defense, to eliminate half a dozen lines of near identical code after each call of new TextField();


The constructor for TextField for some reason takes no parameters, even though you pretty much have to set some properties for an instance you create in code. I added  parameters for the defaultTextFormat, x and y which I was always setting, as well as an optional Boolean to make it right aligned. For those text items that were fairly dynamic and so could change alignment I also added functions to set the alignment and position at the same time.



I enable high quality settings but at the same time enable cacheAsBitmap, which works well as text in the game is rarely updated. In fact cacheAsBitmap is so useful for text it's worth creating a class that overrides TextField just to set it all the time.




function BTDText(fmt:TextFormat, fX:Number = 0, fY:Number = 0,
      bRight:Boolean = false):void {
 
 defaultTextFormat = fmt;
 x = fX;
 y = fY;
 // turn on high quality settings
 antiAliasType = AntiAliasType.ADVANCED;
 embedFonts = true;
 gridFitType = flash.text.GridFitType.SUBPIXEL;
 // width etc.
 width = 1;
 multiline = false;
 selectable = false;
 cacheAsBitmap = true;
 if (bRight) {
  autoSize = TextFieldAutoSize.RIGHT;
 } else {
  autoSize = TextFieldAutoSize.LEFT;
 }
}

function Left(fX:Number = 0):void {
 if (fX > 0) {
  x = fX;
 }
 autoSize = TextFieldAutoSize.LEFT;
}

function Centre(fX:Number = 0):void {
 if (fX > 0) {
  x = fX;
 }
 autoSize = TextFieldAutoSize.CENTER;
}

function Right(fX:Number = 0):void {
 if (fX > 0) {
  x = fX;
 }
 autoSize = TextFieldAutoSize.RIGHT;
}

No comments:

Post a comment