概念就不讲了,直接上代码,只解释重要部分,节约读者时间。

先上效果图:

首先是小飞机类:里面有个draw函数,负责画出小飞机,参数说明是否需要画出尾巴的喷火效果。

package { 
import flash.display.Sprite;
public class Ship extends Sprite {
public function Ship() {
draw(false);
}
public function draw(showFlame:Boolean):void {
graphics.clear();
graphics.lineStyle(2,0xFFFFFF);
graphics.moveTo(10,0);
graphics.lineTo(-10,10);
graphics.lineTo(-5,0);
graphics.lineTo(-10,-10);
graphics.lineTo(10,0);
if (showFlame) {
graphics.moveTo(-7.5,-5);
graphics.lineTo(-15,0);
graphics.lineTo(-7.5,5);
}
}
}
}

下面是主类:重要部分有注释说明。

package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
   //设置背景色为黑色,因为小飞机为白色边框
[SWF(backgroundColor="0x000000")]
public class ShipShim extends Sprite
{
     //ship代表小飞机,vx代表水平速率,vy为垂直速率,vr为角速度,thrust为点火推力
private var ship:Ship;
private var vx:Number = 0;
     private var vy:Number = 0;
        private var vr:Number = 0;
private var thrust:Number = 0;

public function ShipShim()
{  
        //创建小飞机  
ship = new Ship();
ship.x = this.stage.stageWidth / 2;
ship.y = this.stage.stageHeight / 2;
addChild(ship);
//监听键盘事件和enterframe事件
stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP,onKeyUp);
addEventListener(Event.ENTER_FRAME,onEnterFrame);
}

protected function onKeyDown(event:KeyboardEvent):void
{
        //如果按键为上,则显示飞机尾部火焰并设置推力为0.2,如果为左则设置飞机角速度为-5,如果为右则设置飞机小速度为5
switch(event.keyCode)
{
case Keyboard.UP :
ship.draw(true);
thrust = 0.2;break;
case Keyboard.LEFT : 
vr = -5; break;
case Keyboard.RIGHT :
vr = 5; break;
}
}

protected function onKeyUp(event:KeyboardEvent):void
{
        //没有按键则设置角速度和推力为0并显示没有火焰的飞机
vr = 0;
thrust = 0;
ship.draw(false);
}

protected function onEnterFrame(event:Event):void
{
        //首先设置飞机当前角度
ship.rotation += vr;
        //转换当前角度为弧度
var radians:Number = ship.rotation * Math.PI / 180;
        //根据该弧度计算x方向加速度,和y方向加速度
var ax:Number = Math.cos(radians) * thrust;
var ay:Number = Math.sin(radians) * thrust;
        //根据最新加速度计算最新的vx,vy
vx += ax;
vy += ay;
        //根据最新速率计算当前飞机坐标
ship.x += vx;
ship.y += vy;
}
}
}

程序虽简单,但足以体现如何处理flash中的速度和加速度。


posted on 2012-01-18 14:26  再不能这样活  阅读(696)  评论(0编辑  收藏  举报