AARON SMITH’S CODE ENDEAVOR

New KeyHandler Class

I’ve added a new class to replace the KeyManager. The key manager was nice but somewhat complicated internally. I’m replacing it with this new key handler class - It’s similar to the key manager except that it will only handle one key event per instance VS the key manager which would manage every key event you wanted.

I added a new feature called auto target, which will enable, or disable the key handler when the target is removed or added to the stage.

Here’s how you use it:

package
{
	import gs.util.KeyHandler;
	import gs.util.StageRef;
 
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.utils.setTimeout;
 
	public class Main extends Sprite
	{
 
		public var mc:MovieClip;
		private var kh:KeyHandler;
		private var kh2:KeyHandler;
		private var kh3:KeyHandler;
		private var kh4:KeyHandler;
 
		public function Main():void
		{
			//the stage ref needs to be set somewhere
			StageRef.stage=stage;
 
			//create key handlers.
			kh=new KeyHandler("SHIFT+M",onShiftM);
			kh2=new KeyHandler("UP",onUp);
			kh3=new KeyHandler("f",onLetter);
			kh4=new KeyHandler("as",onSequence);
 
			//auto target example (enabled/disabled depending on if the target is on the stage)
			//the "kh" keyHandler won't work when the clip is off the stage.
			kh.autoTarget=mc;
			setTimeout(removeChild,2000,mc);
			setTimeout(addChild,4000,mc);
		}
 
		private function onSequence():void
		{
			trace("sequence as");
		}
 
		private function onLetter():void
		{
			trace("letter f");
		}
 
		private function onShiftM():void
		{
			trace("SHIFT+M");
		}
 
		private function onUp():void
		{
			trace("UP");
		}
	}
}

There’s a functioning example in the guttershark repo.

  

2 Comments so far

  1. Guillaume Malartre February 17th, 2010 6:05 am

    Nice approach, seems useful for Flash project. You could put “UP” and “SHIFT” in static const.

    Here’s my pick for Flex: KeySequenceDetector presented in this post http://gmalartre.blogspot.com/2009/10/retrieve-your-traces-in-actionscript-3.html .

    Thanks for sharing!

  2. admin February 18th, 2010 8:26 pm

    Thanks Guillaume,

    Thanks for that link - good stuff. Definitely checkout the source code from KeyHandler, I think you’ll find some good snippets in it.

Leave a reply