【发布时间】:2011-04-29 04:19:57
【问题描述】:
我可以使用 ActionScript 跟踪按下的键吗?
【问题讨论】:
标签: flash actionscript keylistener
我可以使用 ActionScript 跟踪按下的键吗?
【问题讨论】:
标签: flash actionscript keylistener
我使用了我不久前制作的这个类:
编辑:现在稍微干净了。
package
{
import flash.display.Stage;
import flash.events.KeyboardEvent;
public class Keys extends Object
{
// vars
private var _keys:Array = [];
/**
* Constrcutor
* @param stg The stage to apply listeners to
*/
public function Keys(stg:Stage)
{
stg.addEventListener(KeyboardEvent.KEY_DOWN, _keydown);
stg.addEventListener(KeyboardEvent.KEY_UP, _keyup);
}
/**
* Called on dispatch of KeyboardEvent.KEY_DOWN
*/
private function _keydown(e:KeyboardEvent):void
{
//trace(e.keyCode);
_keys[e.keyCode] = true;
}
/**
* Called on dispatch of KeyboardEvent.KEY_UP
*/
private function _keyup(e:KeyboardEvent):void
{
delete _keys[e.keyCode];
}
/**
* Returns a boolean value that represents a given key being held down or not
* @param ascii The ASCII value of the key to check for
*/
public function isDown(...ascii):Boolean
{
var i:uint;
for each(i in ascii)
{
if(_keys[i]) return true;
}
return false;
}
}
}
从这里开始很简单:创建一个键实例并使用 isDown() 方法。
var keys:Keys = new Keys(stage);
addEventListener(Event.ENTER_FRAME, _handle);
function _handle(e:Event):void
{
if(keys.isDown(65)) trace('key A is held down');
}
它甚至可以一次检查多个键:
if(keys.isDown(65, 66)) // true if 'a' or 'b' are held down.
编辑:
当您使用 compile (ctrl+enter) 来禁用键盘快捷键(控制 -> 禁用键盘快捷键)进行测试时,这也很有帮助。
【讨论】: