PDA

View Full Version : enemy walking back and forth AI in actionscript 3



cr1pl3d
February 6th, 2009, 08:31 PM
I'm trying to create AI for enemies in my game to walk back and forth and since I'm new to this I'm completely lost. can anyone show me code on how to do this, I would greatly appreciate it. All I have now is a box that is a MC as a test for my AI.

snottlebocket
February 7th, 2009, 04:44 PM
Well in the most simple terms, moving a movieclip is a simple matter of adding or substracting to it's x position.

For instance mc.x + 5 will add five pixels to it's current x position thus moving it to the right, if you put that inside a repeating function for example an EnterFrame listener, it'll continually move.

Since you know how much you'll be adding to your mc's position, you also know where it's going to be, which means you can check on whether or not it should turn around.

Let's say your movieclip is standing on an imaginary platform that is 100 pixels wide, that means that once it's x position is greater than 100 pixels, it should really turn around again.

addEventListener(Event.ENTER_FRAME, mover){
speed = 5; //move five pixels per frame, pretty fast
if(mc.x + speed > 100){
speed *= -1; //if adding the speed to the movieclip would cause the movieclip to go beyond 100px, inverse the speed
mc += speed;// move to the right
}
else{
mc.x += speed;
}
}

The above tit bit of pseudo script causes a movieclip to steadily move to the right, then turn around once it would go past 100px and head left again, I'm sure you can imagine you could cause it to turn around and head to the right again if it would pass the 0 pixel boundary (ie the left side of your screen)

What you use as your boundary is entirely up to you, if you place him on a platform movieclip you know both the x position and the width of your platform so you can calculate boundaries based on that.