玩家的功能已经全部完成,开始完成敌方的AI
敌方坦克也可以随机做一下几个动作
1.移动,2.发射子弹,3.转向
为了看起来效果更好一点,移动应该最大比例,发射子弹和转向应该比较少
首先要有个随机方法
1 public randomNum(minNum:number,maxNum:number){
2 switch(arguments.length){
3 case 1:
4 return Math.random()*minNum+1;
5 case 2:
6 return Math.random()*(maxNum-minNum+1)+minNum;
7 default:
8 return 0;
9 }
10 }
实现随机逻辑
1 private doEnemyAI() {
2 // 敌方坦克AI,随机发射,转向,移动
3 if(Main.enemyList.length <= 0) {
4 return;
5 }
6 for(let idx=Main.enemyList.length; idx>=0; idx--) {
7 let enemy:Tank = Main.enemyList[idx];
8 if(enemy == null) {
9 continue;
10 }
11 let rand = this.randomNum(1,100);//
12 if(rand >= 98) {// 转向 5%
13 enemy.turnRand();
14 } else if(rand >= 96) {// 发射子弹 10%
15 enemy.shoot();
16 } else {// 移动 94%
17 enemy.moveFront();
18 }
19 }
20 }
最后还要处理子弹,发射后子弹要延原来方向一直向前运动,运动过程中要判断是否遇到砖块,是否遇到石头,是否遇到玩家坦克,是否超出边界,如果是玩家的子弹,要判断是否遇到地方坦克
private handleBullet() {
// 子弹逻辑
if(Main.bulletList.length <= 0) {
return;
}
for(let idx=Main.bulletList.length; idx>=0; idx--) {
let bullet:Bullet = Main.bulletList[idx];
if(bullet == null) {
continue;
}
bullet.move()
// 判断是否到边界
if(bullet.x <= 0 || bullet.y <= 0) {
// 移除子弹
Main.bulletList.splice(idx,1);
bullet.parent.removeChild(bullet);
continue;
}
if(bullet.x >= 640 || bullet.y >= 640) {
// 移除子弹
Main.bulletList.splice(idx,1);
bullet.parent.removeChild(bullet);
continue;
}
// 判断是否撞倒墙
let tile:tiled.TMXTile = this.layerZhuan.getTile(bullet.x, bullet.y);
if(tile) {
console.log('---x,y', tile.x, tile.y);
// 移除子弹
Main.bulletList.splice(idx,1);
bullet.parent.removeChild(bullet);
// 移除砖块
this.layerZhuan.clearTile(tile.tileX, tile.tileY);
tile.bitmap.parent.removeChild(tile.bitmap);
continue;
}
// 判断是否撞到石头
tile = null;
tile = this.layerShitou.getTile(bullet.x, bullet.y);
if(tile) {
// 移除子弹
Main.bulletList.splice(idx,1);
bullet.parent.removeChild(bullet);
}
// 判断是否撞倒其他坦克
for(let j=Main.enemyList.length; j>=0; j--) {
let enemy:Tank = Main.enemyList[j];
if(enemy == null) {
continue;
}
if(enemy.hitTestPoint(bullet.x, bullet.y)) {
if(bullet.tank.camp == 'player') {
Main.enemyList.splice(j,1);
enemy.parent.removeChild(enemy);
}
}
}
// 判断是否撞到玩家
if(this.player1 && bullet.tank.camp == 'enemy') {
if(this.player1.hitTestPoint(bullet.x, bullet.y)) {
this.player1.parent.removeChild(this.player1);
this.player1 = null;
}
}
}
}
最后附上游戏试玩地址http://521100.net/games/tank/index.html
来源:https://www.cnblogs.com/woaitech/p/12242375.html