Not just Actionscript noodlings


19 Oct

Making sure something is on the stage


Sometimes you will need a class to be on the stage before you can use it. For example, when using the stage properties like stage.stageWidth and stage.stageHeight.

I have found the following to work the best:

package
{
	public class DisplayItem extends Sprite
	{
		public function SomeClass ()
		{
			addEventListener(Event.ADDED_TO_STAGE, init);		
		}
 
		private function init(event:Event):void
		{
			//It's always best to remove any event listeners once you dont need them any more.
			event.target.removeEventListener(Event.ADDED_TO_STAGE, init);
 
			trace("stage height = "+stage.stageHeight);
			trace("stage width = "+stage.stageWidth);
		}
	}
}

19 Oct

Centering anything


This is the simplest way to center anything.

anyThing = new AnyThing();
anyThing.x = (stage.stageWidth * 0.5) - (anyThing.width * 0.5);
anyThing.y = (stage.stageHeight * 0.5) - (anyThing.height * 0.5);
addChild(anyThing);