3、敌方移动
先把enemy放到地图中,初始化它的一些属性。
function attachEnemies() {
for (i=0; i<enemies.length; i++) {
boxes.attachMovie('enemy', 'enemy'+i, 810+i);//加载该mc
boxes['enemy'+i]._x = 10+(enemies[i][1]*20);//
boxes['enemy'+i]._y = 10+(enemies[i][0]*20);//设置它的位置
boxes['enemy'+i].speed = 1;//移动速度
boxes['enemy'+i].shooting = false;//射击状态
boxes['enemy'+i].viewlimit = 15;//视力范围
boxes['enemy'+i].onEnterFrame = function() {
if (this._currentframe == 1) {如果没被击中
checkForEnemy(this);
} else {
}
};
}
}
enemy移动:
function enemyMove() {
clearBoxes();//重置地图;
for (p=0; p<enemies.length; p++) {
if (boxes['enemy'+p]._currentframe == 1) {//如果敌人没被击中
j = Math.round(Math.random()*(boxes['enemy'+p].moveable.length-1));//随机的获得一个方向
boxes['enemy'+p]._x = (boxes['enemy'+p].moveable[j][1]*20)+10;
boxes['enemy'+p]._y = (boxes['enemy'+p].moveable[j][0]*20)+10;//enemy的移动位置
enemyBrain(boxes['enemy'+p]);//重新计算它的视力范围和可移动的路线
} else {
}
}
}
function clearBoxes() {
for (n=0; n<ymax; n++) {
for (m=0; m<xmax; m++) {
if (boxes['b'+n+'_'+m]._alpha == 50) {
boxes['b'+n+'_'+m]._alpha = 100;
}
}
}
}
该函数首先被执行:
function enemyBrain(a) {
a.sight = new Array();//视力范围
a.moving = new Array([1, 0], [0, 1], [-1, 0], [0, -1]);//移动的四个方向
a.moveable = new Array();
a.view = _root.view;//八个方向
a.boxes = a._parent;
a.xpos = Math.round((a._x-(a._width/2))/20);//enemy的位置转换成数组下标
a.ypos = Math.round((a._y-(a._height/2))/20);
for (k=0; k<a.moving.length; k++) {//
if (boxes['b'+(a.ypos+a.moving[k][0])+'_'+(a.xpos+a.moving[k][1])]._currentframe == 1) {//如果是道路
a.moveable.push([(a.ypos+a.moving[k][0]), (a.xpos+a.moving[k][1])]);//保存到可走路线数组中
}
}
for (i=0; i<a.view.length; i++) {//八个方向(考虑子弹的移动路线)
for (j=1; j<a.viewlimit; j++) {//视力范围限制
if (boxes['b'+(a.ypos+(a.view[i][0]*j))+'_'+(a.xpos+(a.view[i][1]*j))]._currentframe == 2) {//如果是墙壁
break;
} else {
a.sight.push([(a.ypos+(a.view[i][0]*j)), (a.xpos+(a.view[i][1]*j))]);射击范围存入数组
// boxes['b'+(a.ypos+(a.view[i][0]*j))+'_'+(a.xpos+(a.view[i][1]*j))]._alpha = 50;
}
}
}
}
function checkForEnemy(z) {
z.man = z._parent.man;//获得man的位置
z.manxright = Math.round((z.man._x-(z.man._width/2))/20);
z.manxleft = Math.round((z.man._x-15)/20);
z.manybottom = Math.round((z.man._y-15)/20);
z.manytop = Math.round((z.man._y-(z.man._height/2))/20);//转换成数组的下标
for (u=0; u<z.sight.length; u++) {//子弹的射程
if (z.manxleft == z.sight[u][1] or z.manxright == z.sight[u][1]) {
if (z.manytop == z.sight[u][0] or z.manybottom == z.sight[u][0]) {//如果有两个点在射程之内
shootEnemy(z, z.sight[u][0], z.sight[u][1]);//开始向该方向射击
}
}
}
}
以上的几个函数都做了详细的注释,实现了enemy的移动和视力范围的监控。enemy的移动是随机的,有一个setInterval函数来控制移动数据的刷新。每次刷新,enemy都会从当前的四个方向的邻近的方块内选择是道路的方块来移动。与此同时,还会收集视力范围之内的方块的情况,这里由于它是根据方向进行信息的收集,收集的是8个方向的方块的情况,如果遇到了墙壁的话,它的本次循环就会终止。这样就保证了墙壁在游戏中的作用。
浅蓝色是视力范围,你很快就会发现这种算法的bug很多的区域他是看不到的
回复Comments
作者:
{commentrecontent}