[MX] Problems understanding part of AI script
I have been working through an example of a basic AI script from Jobe Makar's excellent book
“Flash MX games design demystified” there is one section that has really got me stumped.
Basically there are baddies that chase a goodie – code runs to determine where the hero is relative to the bad guys -1 if he is to the left 0 same column 1 to the right + similar sort of thing for “up” & “down” The result is alocated to the variables xsign & ysign now the part I'm having problems with is this section
Code:
if (xsign == ysign || xsign == -ysign) {
var ran = random(2);
if (ran == 0) {
var xsign = 0;
} else {
var ysign = 0;
}
}
this is supposed to tell us if the baddie is in the same row or column – but i can't see how.
I have set out the whole function (part of a larger script) below so you can see it in context, but if anyone can explain how the above achieves what it is supposed to i would be grateful.
Code:
function baddyAI() {
for (var i = 0; i<game.baddies.length; ++i) {
var ob = game.baddies[i];
++ob.time;
var cell_x = Math.ceil(ob.x/game.cellWidth);
var cell_y = Math.ceil(ob.x/game.cellWidth);
var cell_over = game.tiles[cell_x][cell_y];
var cell_x_temp = Math.ceil(ob.tempx/game.cellWidth);
var cell_y_temp = Math.ceil(ob.tempy/game.cellWidth);
var cell_over_temp = game.tiles[cell_x_temp][cell_y_temp];
if (!cell_over_temp.empty || ob.time == ob.maxtime) {
ob.time = 0;
ob.maxtime = 30+random(30);
ob.tempx = ob.x;
ob.tempy = ob.y;
var tempDir = ob.dir;
var xmov = 0;
var ymov = 0;
var speed = Math.abs(ob.speed);
var xsign = (game.char.x-ob.x)/Math.abs((game.char.x-ob.x));
var ysign = (game.char.y-ob.y)/Math.abs((game.char.y-ob.y));
if (random(10) == 0) {
var xsign = -1*xsign;
var ysign = -1*ysign;
}
if (xsign == ysign || xsign == -ysign) {
var ran = random(2);
if (ran == 0) {
var xsign = 0;
} else {
var ysign = 0;
}
}
if (xsign != 0) {
var ymov = 0;
var xmov = xsign*speed;
if (xmov>0) {
var dir = "right";
} else {
var dir = "left";
}
} else if (ysign != 0) {
var xmov = 0;
var ymov = ysign*speed;
if (ymov>0) {
var dir = "down";
} else {
var dir = "up";
}
}
ob.dir = dir;
ob.clip.gotoAndStop(dir);
ob.xmov = xmov;
ob.ymov = ymov;
}
}
}