Friday, December 19, 2014

#AS3 KeyboardHandler

(i've posted this as a comment in Starling bug report from a user)

for performance crucial sections such as keyboard interaction i would not use anything but callbacks.
the flash event system, and the alternatives such as signals are nice for higher level management, but they can't really beat callbacks for performance. what Starling does with the enhanced events is also fast, but here is my point.
the virtual machine and the garbage collector already provide you with the flexibility of one of the core features - everything is an Object including Function.
"functors" or function pointers is something that even languages like C++ don't handle that well, so you really should take advantage of this low level, yet still high level feature.
since the only way in flash to see if a key is pressed is via the KeyboardEvent, use that and build a callback system on top of it. only maintain the stage events and propagate manually not display objects but rather objects of interest.
check this concept i wrote quickly:
  • KeyboardHandler is a state machine that tracks keyboard isDown states for a keyCode and calls your registered callback.
  • it uses the native stage
  • it's super fast
  • it's worker safe
  • you can stop it at any time using "enabled = false"
  • it does call event.preventDefault(), event.stopImmediatePropagation(), but you can mod that yourself or simply call "enabled = false" when needed.
  • once a key is down it no longer registers as down until it up, this forces you to write your key logic smart.
  • if you don't track a key state yourself (which would be faster) at any time you can call supportedKeyIsDown(...) to see if a key is currently down. this allows easy checks for key combinations e.g ALT + SHIFT + LEFT.

0 comments: