创建按键侦听
//创建一空剪辑ship_mc画飞船
this.createEmptyMovieClip("ship_mc", this.getNextHighestDepth());
function drawShip(flag:Boolean):Void {
with (ship_mc) {
clear();
lineStyle(1, 0xffffff);
moveTo(10, 0);
lineTo(-10, -10);
lineTo(-5, 0);
lineTo(-10, 10);
lineTo(10, 0);
//是否显示飞船加速时的尾气
if (flag) {
moveTo(-7.5, -5);
lineTo(-15, 0);
lineTo(-7.5, 5);
}
}
}
//初始状态不显示尾气
drawShip(false);
//初始化飞船位置
ship_mc._x = Stage.width/2;
ship_mc._y = Stage.height/2;
//初始化旋转的角速度,加速时加速度所对应的力,x、y方向的初始速度
var vr:Number = 0;
var force:Number = 0;
var vx:Number = 0;
var vy:Number = 0;
//添加侦听键盘,左右上方向的按键
obj = new Object();
obj.onKeyDown = function(obj:Object) {
if (Key.isDown(Key.LEFT)) {
//左方向键,顺时针旋转
vr += 5;
} else if (Key.isDown(Key.RIGHT)) {
//右方向键,逆时针旋转
vr -= 5;
} else if (Key.isDown(Key.UP)) {
//向上方向,施加一个力force,显示尾气
force = 0.2;
drawShip(true);
}
};
obj.onKeyUp = function(obj:Object) {
//释放按键后操作
vr = 0;
force = 0;
drawShip(false);
};
Key.addListener(obj);
//执行函数
this.onEnterFrame = function() {
//控制飞船的旋转,如果长时间按住方向键,飞船将旋转越来越快;
ship_mc._rotation += vr;
var angle:Number = ship_mc._rotation*Math.PI/180;
//跟据飞船的方向将力所产生的加速度分解为x,y方向
var ax:Number = force*Math.cos(angle);
var ay:Number = force*Math.sin(angle);
//移动飞船
vx += ax;
vy += ay;
ship_mc._x += vx;
ship_mc._y += vy;
};
补充:flash教程,As3.0