# Enemy Movement and Pacing

I’m creating a 2D platformer and I’m working on getting some small enemies wandering around that will hurt the player. My plan for now is to just have them pace back and forth. Their script is as follows:

``````public class MinionScript : MonoBehaviour
{

float speed = 20.0f;
float origX;

// Use this for initialization
void Start ()
{
//Vector3 origPosition = transform.position;
origX = transform.position.x;
}

// Update is called once per frame
void Update ()
{
transform.Translate(speed*Time.deltaTime,0,0);

if(Mathf.Abs(origX - transform.position.x) > 5.0f)
{
speed *= -1.0f; //change direction
}
}
}
``````

I’m having trouble with the movement (the only thing defined in Update()). Sometimes it will pace, other times it will stutter and vibrate in one place, as if it’s quickly changing directions. Why might this be? Is there a better way to get this enemy to pace?

other times it will stutter and vibrate in one place

Let’s say your enemy move to right when the game start, when the enemy reached the end of their march, `transform.position.x` will be larger than 5.0f (let’s say 5.15f), then you flipped the speed (speed now becomes -20f).

In the next `Update()`, there are chances that that the `Time.deltaTime` is just small enough, so that your `transfrom.position.x` become 5.05f instead of smaller than 5f (4.9f something). Then you flipped again, speed now becomes 20f.

In the next `Update()`, your enemy will move slightly to the right (`transform.position.x` = 5.20f ), and the speed is flipped again. This will become a vicious cycle that makes the enemy stuck on same spot. (The position.x is going back and forth in such a way: 5.2, 5.05, 5,23, 5.07, 5.3, 5.1, 5.2, 5.05 … )

Correction on your logic:

``````private float useSpeed;

...

if( origX - transform.position.x > 5.0f)
{
useSpeed = -speed;
}
else if ( origX - transform.position.x < -5.0f ) {
useSpeed = speed;
}

transform.Translate(useSpeed*Time.deltaTime,0,0);
``````