前面讲解了Flash AS3教程:Direction类和Dot类前面都是理论讲解这篇来个实战做个类似坦克游戏
个类似坦克游戏demo
使用Direction类来进行方向控制
使用Dot类来计算距离
用上Direction类和Dot类的后这个demo变得异常简单额
也没什么好说主要透过这个例子让大家类熟悉Direction类和Dot类使用思路方法
不懂可以在后面跟帖提问高手如果看到什么有地方请指正出来多谢指教
下面是fla源代码:
CODE:
import index.base.game.Direction;
import index.base.events.DirectionEvent;
import index.base.geom.Dot;
//舞台属性设置
stage.showDefaultContextMenu = false;
stage.align = "TL";
stage.scaleMode = "noScale";
//创建坦克
var tank:Tank = Tank;
tank.x = tank.y = 250;
addChild(tank);
//创建绑定坦克点
var dot:Dot = Dot;
dot.bind(tank);
//坦克移动
var dirTank:Direction = Direction(stage);
//炮台转动
var dirTower:Direction = Direction(stage,true,87,83,65,68);
//坦克炮台事件
dirTank.addEventListener(DirectionEvent.DO,doTankFun);
dirTower.addEventListener(DirectionEvent.DO,doTowerFun);
//坦克移动
function doTankFun(e:DirectionEvent):void{
(e.up){
dot.go(2,true);
}
(e.down){
dot.go(-2,true);
}
(e.left){
tank.rotation -= 2;
}
(e.right){
tank.rotation 2;
}
(tank.x < 0) tank.x = 0;
(tank.y < 0) tank.y = 0;
(tank.x > stage.stageWidth) tank.x = stage.stageWidth;
(tank.y > stage.stageHeight) tank.y = stage.stageHeight;
}
//是否可以发射炮台子弹
var isBullet:Boolean = true;
var isShell:Boolean = true;
//炮台发射转动
function doTowerFun(e:DirectionEvent):void{
(e.up && isBullet){
var bullet:Bullet = Bullet;
bullet.x = tank.x;
bullet.y = tank.y;
bullet.rotation = tank.rotation + tank.tower.rotation;
bullet.addEventListener(Event.ENTER_FRAME,bulletFun);
addChild(bullet);
isBullet = false;
Timeout(function{isBullet = true},200);
}
(e.down && isShell){
var shell:Shell = Shell;
shell.x = tank.x;
shell.y = tank.y;
shell.rotation = tank.rotation;
shell.addEventListener(Event.ENTER_FRAME,shellFun);
addChild(shell);
isShell = false;
Timeout(function{isShell = true},500);
}
(e.left){
tank.tower.rotation -= 5;
}
(e.right){
tank.tower.rotation 5;
}
}
//炮台
function shellFun(e:Event):void{
var tmp:Shell = e.currentTarget as Shell;
var d:Dot = Dot(tmp.x,tmp.y,tmp.rotation);
d.bind(tmp);
d.go(4,true);
(tmp.x < 0 || tmp.x > stage.stageWidth || tmp.y < 0 || tmp.y > stage.stageHeight){
removeChild(tmp);
tmp.removeEventListener(Event.ENTER_FRAME,shellFun);
}
tmp = null;
d = null;
}
//子弹
function bulletFun(e:Event):void{
var tmp:Bullet = e.currentTarget as Bullet;
var d:Dot = Dot(tmp.x,tmp.y,tmp.rotation);
d.bind(tmp);
d.go(5,true);
(tmp.x < 0 || tmp.x > stage.stageWidth || tmp.y < 0 || tmp.y > stage.stageHeight){
removeChild(tmp);
tmp.removeEventListener(Event.ENTER_FRAME,bulletFun);
}
tmp = null;
d = null;
}
另外注意源代码有个地方多次对tanktower属性就行引用并且返回他xy或者旋转值有人就会问了as3不是不支持类似mc那样直接访问显示对象为什么我这儿却可以?
愿意是我把素材绑定在Tank类上并且对Tank类做了以下编写:
CODE:
package{
import flash.display.Sprite;
public Tank extends Sprite{
public function Tank{
}
public function get tower:Sprite{
towerMc;
}
}
}
光看这个类也许你还是不明白是什么原因为什么会多出来个towerMc出来详细原因请自己下载提供源文件下载下来看看吧不懂跟帖问!
最新评论