|
  
- 帖子
- 3825
- 积分
- 711
- 技术分
- 155
- 来自
- 大家闪才是真的闪
- 在线时间
- 1429 小时
- 注册时间
- 2003-2-2
|
8#
发表于 2007-11-21 11:10
| 只看该作者
我也来写发一个按键的,无按钮按下的时候不进行真检测,省资源~
//Key.as- package CYPL.Game{
- import flash.display.InteractiveObject;
- import flash.events.KeyboardEvent;
- import flash.events.Event;
- public class Key {
- private static var keyObj:Object;
- private static var io:InteractiveObject;
- private static var keyTestHandler:Function;
- public static function init(io:InteractiveObject,keyTestHandler:Function):void {
- Key.io=io;
- Key.keyTestHandler=keyTestHandler;
- keyObj=new Object ;
- io.addEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);
- io.addEventListener(KeyboardEvent.KEY_UP,keyUpHandler);
- }
- public static function isDown(key:int):Boolean {
- return !!keyObj[key];
- }
- private static function keyDownHandler(e:KeyboardEvent):void {
- keyObj[e.keyCode]=true;
- io.addEventListener(Event.ENTER_FRAME,keyTestHandler);
- }
- private static function keyUpHandler(e:KeyboardEvent):void {
- delete keyObj[e.keyCode];
- keyObjHasProperty()?removeKeyTestHandler():null;
- }
- private static function keyObjHasProperty():Boolean {
- for each (var j:Boolean in keyObj) {
- if (j) {
- return false;
- }
- }
- return true;
- }
- private static function removeKeyTestHandler():void {
- io.removeEventListener(Event.ENTER_FRAME,keyTestHandler);
- }
- public static function get KeyObj():Object {
- return Key.keyObj;
- }
- }
- }
复制代码 使用:- import CYPL.Game.Key;
- var box:Sprite;
- with (box=Sprite(addChild(new Sprite))) {
- graphics.beginFill(0xff0000);
- graphics.drawRect(100,100,100,100);
- }
- Key.init(stage,keyTestHandler);
- function keyTestHandler(e:Event) {
- if (Key.isDown(Keyboard.LEFT)) {
- box.x-=5;
- }
- if (Key.isDown(Keyboard.RIGHT)) {
- box.x+=5;
- }
- if (Key.isDown(Keyboard.DOWN)) {
- box.y+=5;
- }
- if (Key.isDown(Keyboard.UP)) {
- box.y-=5;
- }
- }
复制代码 [ 本帖最后由 ycccc8202 于 2007-11-21 11:13 编辑 ] |
-
-
key.rar (5.76 KB)
|