7 Replies Latest reply on Aug 26, 2011 7:14 AM by Ned Murphy

# Easy enemy movement

I need help with some code. I'm trying to get the enemy offstage to enter the stage on the right and then once its x position equals 400 I want it to start moving back and forth (on x, there's no y movement). Any help would be appreciated.

• ###### 1. Re: Easy enemy movement

What code do you currently have that you need help with?

• ###### 2. Re: Easy enemy movement

I tried a couple things that got me nowhere so I went back to scratch. Right now it's:

```//Start the Boss off the right edge of the stage
_x = 700;
_y = 342;
//set the Boss's horizontal speed to 3.
speed = 3;
//Add this enemy to the ship's list of enemies, its enemies array
_root.ship.enemies.push(this);
//Set the Boss's shoot timer to zero
shootTimer = 0;
}

function onEnterFrame()
{
// --- HORIZONTAL MOVEMENT LOGIC---
if(_x > 400)
{
//move it to the left 3 pixels (we set the speed to 3 in the onLoad() function)
_x -= speed;

}
```
• ###### 3. Re: Easy enemy movement

With some repair (removing the errant curly nracket) that code would get your object moving to stop at _x = 400.

//Start the Boss off the right edge of the stage
_x = 700;
_y = 342;
//set the Boss's horizontal speed to 3.
speed = 3;
//Add this enemy to the ship's list of enemies, its enemies array
_root.ship.enemies.push(this);
//Set the Boss's shoot timer to zero
shootTimer = 0;

this.onEnterFrame = function()
{
if(_x > 400)
{
_x -= speed;
}
}

So what do you want it to do that you are describing as "moving back and forth " after it gets to 400?

• ###### 4. Re: Easy enemy movement

I mean continually move left and right by maybe 50 pixels or so, or maybe a random value, whatever is easier. I just don't want it to sit in one place when it gets there.

• ###### 5. Re: Easy enemy movement

One way to do this is to delete the enterframe once the first phase completes and assign another function for an enterframe for the next phase where you change the speed by multiplying it by -1 each time it exceeds the upper or lower limits you decide on.  That way your speed will change between -3 and +3.

So in your second phase enterframe function you test to see if the object is within a particular range (your upper and lower limits) and when it exceeds that range you switch the sign of the speed so that the object travels the other way.

_x = 700;
_y = 342;
speed = 3;
_root.ship.enemies.push(this);
shootTimer = 0;

this.onEnterFrame = enterStage;

function enterStage()
{
if(_x > 400)
{
_x -= speed;
} else { // it has reached 400 so start 2nd phase
delete this.onEnterFrame;
speed *= -1;
this.onEnterFrame = oscillate;
}
}

function oscillate(){
if(_x < 350 || _x > 450){
speed *= -1;
}
_x -= speed;

}

• ###### 6. Re: Easy enemy movement

That did exactly what I wanted, thank you.

• ###### 7. Re: Easy enemy movement

You're welcome