简介
今天是开发飞行射击游戏第四天,NPC机制和攻击血量效果。
实现敌机阵列效果出现和玩家子弹击中敌机NPC 血量减少至0消失。
欢迎大家和我一起学习哦~ 下面是详细过程代码,还有遇到的错误以及改正方法。
实现效果
代码及过程
一 .NPC是个数不确定的对象,需要使用工厂。
所有被工厂管理的对象都要有vis属性,只要=false,就消失。
1)创建NPC类和NPCManager类
public game:MainGame;
public im:egret.Bitmap[] = []; //2张拼起来的图片所以用数组 //这里出现错误,原来写到
public vy:number; //速度
public vis:boolean; //工厂生存属性
public nm:NPCManager; //上级指针
public constructor(x:number,y:number,vy:number,nm:NPCManager) {
super();
this.nm = nm;
this.x = x ;this.y = y;
this.vy = vy;
//这个NPC是2张图片拼起来的所以第二张翻转正好拼成一个。为什么是半个图片,节省资源
this.im[0] = Main.createBitmapByName("npc5_png");
this.im[0].anchorOffsetX = this.im[0].width;
this.im[0].anchorOffsetY = this.im[0].height/2;
this.addChild(this.im[0]);
this.im[1] = Main.createBitmapByName("npc5_png");
this.im[1].anchorOffsetX = this.im[1].width;
this.im[1].anchorOffsetY = this.im[1].height/2;
this.im[1].scaleX = -1;
this.addChild(this.im[1]);
this.vis = true;
}
public update(){
this.y +=this.vy;
if(this.y > 1000){
this.vis = false;
}
}
出现的错误:
public im:egret.Bitmap[] = [];
原来写的public im:egret.Bitmap[]; 没有写=[ ]; 应该加强记忆
整理:完成一个NPC,但是游戏需要多个NPC,需要使用工厂管理,工厂需要create方法生成,同时,create方法生成的需要放到仓库中,再把仓库中的对象一个一个更新update。
只要是管理个数可变的对象,所有的工厂代码都是一样的,
2)NPCManager类
把ZDManager中代码全复制到NPCManager中名字相应修改就可以
public nm:Array; //Array动态数组(容器),通过添加,添加对象,移除对象。
public game:MainGame;
public constructor(game:MainGame) {
super();
this.game = game;
this.nm = new Array();
}
//每create一次就new一个
public create(x:number,y:number,v:number){
//生成子弹
let one = new NPC(x,y,v,this);
//添加到世界
this.addChild(one);
//放到仓库数组最后
this.nm.push(one);
}
//更新所有子弹,找到每一颗子弹,每颗更新
public update(){
//整个仓库长度 ,利用循环可以循环出所有子弹
for(let i = 0 ; i < this.nm.length ; i++){
//找到每颗子弹
let one = this.nm[i];
one.update();
//若子弹太多,仓库会满,所以子弹需要移除
//子弹出屏,vis == false。移除
if(one.vis == false){
//先从场景移除
this.removeChild(one)