Learn how to make your enemy move and to follow the player around the stage using basic artificial intelligence. It might be useful to follow my player movement tutorial before embarking on thisone.
Step One
Create a new movieclip and name its instance 'enemy'. Inside the movieclip, on a new layer, we are going to add a walk function. Call this function 'walkTo' and give it the variables X and Y. We will add the code within this function in a couple of steps.
function walkTo(X, Y) {
}
scooters
Step Two
Now, before we begin writing the 'walkTo' function it might be helpful if we add a call to it so we can see what we are doing as changes are being made. On the main timeline, on the enemy instance add this code.
onClipEvent (enterFrame) {this.walkTo(_root.player._x, _root.player._y);}
This will call our walkTo function and also give it the coordinates of the player movieclip too.
Step Three
We are now ready to begin writing our walkTo script. Within the walkTo function, let's first add a speed variable.
Next, lets deal with vertical movement on the Y-axis. If say, the enemy had a co-ordinate of 300 and the player was at 100, the enemy would have to reduce its Y co-ordinate in order equal that of the player's. We can do this by subtracting our speed variable. Here's how we'll do it.function walkTo(X, Y) {var speed = 3;
}
function walkTo(X, Y) {
var speed = 3;
// Y-Axis movement
if (this._y>(Y)) {
this._y -= speed;
}
}
function walkTo(X, Y) {
var speed = 3;
// Y-Axis movement
if (this._y>(Y)) {
this._y -= speed;
} else if (this._y<(Y)) {
this._y += speed;
}
}Once done, you will see that the enemy can now move either up or down. But hold on, there seems to be some jittering going on when the enemy has equalled the player's Y co-ordinate. This is because the two if statements are flip-flopping between each other. We need to create a margin so that both statements can be happy. Do this simply by adding and subtracting a little from each of the statements targets. This means that the movieclip can find a nice resting spot between the two points.
// Y-Axis movement
if (this._y>(Y+20)) {this._y -= speed;} else if (this._y<(Y-20)) { this._y += speed;
}
Step Four
Now that we have our vertical movement sorted out, let add some horizontal. It works in exactly same way. You'll notice that also have new line which alters the _xscale. This makes sure the movieclip faces left when walking left and faces right when walking right.
function walkTo(X, Y) {
var speed = 3;// Y-Axis movement
if (this._y<(Y-20)) {this._y += speed;} else if (this._y>(Y+20)) {
this._y -= speed;}// X-Axis Movement
if (this._x<(X-40)) {this._x += speed;this._xscale = -100;} else if (this._x>(X+40)) {
this._x -= speed;
this._xscale = 100;
}
}