# 2D Enemy AI X-way only

I tried learn tutorial from youtube that about "myTransform.position += myTransform.position.forward * moveSpeed * Time.deltaTime;" and its for XYZ.

then i tried made for 2D Enemy walk X-way only but the problem is always enemy went abnormal and run away from the screen view.

here code:

``````function enemymovement() {

enemytransform.transform.position.x += targetat.transform.position.x * moveSpeed * Time.deltaTime;

if (enemytransform.transform.position.x >= HiddenCubeLeft.transform.position.x) // Limit +X
{
enemytransform.transform.position.x = HiddenCubeLeft.transform.position.x + 0.1;
return;
}
else if (enemytransform.transform.position.x >= HiddenCubeRight.transform.position.x) // Limit -X
{
enemytransform.transform.position.x = HiddenCubeRight.transform.position.x - 0.1;
return;
}
}

``````

I did inserted "enemymovement();" in function Update.

There are a few problems...

1) I think there's something wrong with your greater than and lesser then signs... Basically they re the same for boths side. I m just guessing cause i fdont know what "HiddenCudeLeft" and "HiddenCubeRight" is...

if (enemytransform.transform.position.x >= HiddenCubeLeft.transform.position.x) else if (enemytransform.transform.position.x >= HiddenCubeRight.transform.position.x)

prob should be something like

if (enemytransform.transform.position.x >= HiddenCubeLeft.transform.position.x) else if (enemytransform.transform.position.x <= HiddenCubeRight.transform.position.x)

2) This is prob the problem with it runing all over the place.

enemytransform.transform.position.x += targetat.transform.position.x * moveSpeed * Time.deltaTime;

... should just be...

enemytransform.transform.position.x += moveSpeed * Time.deltaTime;

3) also, I ll prob structure the function like this...

``````function enemymovement() {

if (enemytransform.transform.position.x >= HiddenCubeLeft.transform.position.x) // Limit +X
enemytransform.transform.position.x = HiddenCubeLeft.transform.position.x + 0.1;

else if (enemytransform.transform.position.x <= HiddenCubeRight.transform.position.x) // Limit -X
enemytransform.transform.position.x = HiddenCubeRight.transform.position.x - 0.1;

enemytransform.transform.position.x += moveSpeed * Time.deltaTime;
return;
}

``````