flash游戏基本操作:上下左右的移动

 发一个按键无按钮的,按下的时候不进行帧的检测,省资源,AS3制作的。试试效果:
[1b]//Key.as:[/1b]
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;
  }
}
}
[1b]使用:[/1b]
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;
}
}[1b]附件下载:
[img]/Files/BeyondPic/2007-11/21/rar.gif[/img]
 
[url=http://www2.flash8.net/UploadTeach/200711/20071121114545342.rar]key.rar[/url]
[/1b]
本文转自:http://www.5uflash.com/flashjiaocheng/Flash-as3-jiaocheng/1993.html
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值