# how to tell a game object to move between 2 points(A,B) along x axis , right to left, and then move left to right back to its first position ???

hi . im making a 2d game and i have a sphere as an enemy . i want to move this sphere between 2 diffrent positions along the x axis just like old super mario enemies whom could move between 2 points . i mean first move to the left then when it gets to the (A) , move to the right direction to the (B) and also have rotation while moving to left and right . but i dont know what should i use , or what kind of function i can use to make this happen. or is there anything like that available in unity to make this ? need some guids and tips . tnx alot .

right now im using this code :

var enemySpeed : float;

var rotationSpeed : float;

function Update ()

{

amtToMove = enemySpeed * Time.deltaTime;

transform.Translate(Vector3.left * amtToMove);

enemyRotationSpeed = rotationSpeed * Time.deltaTime;

transform.Rotate(Vector3(0,0,0.5) * enemyRotationSpeed , Space.World);

}

the code is working well . its just moving to the left but dont know how am i suppose to tell him to rotate and move right when u get to for example (A) POINT .
another problem is that when its rotating it keeps going downward into the floor! i have a rigid body with is kinematic on my enemy object .
tnx guys

have two empty game objects with triggers and name one A and the other B. tell your enemy look at the point A with the lookAt function and set its velocity to make it move forward on entering the A trigger set the object to look at target B and vis versa.

also rotate it on the y axis, not the z axis, (or maybe i have this reversed in my head but i donâ€™t think so) or else it will move into the ground.

you need to separate

for moving part
you need a boolean to know if moving left or moving right

if(moving)
{
amtToMove = enemySpeed * Time.deltaTime;
if(movingleft)
transform.Translate(Vector3.left * amtToMove);
if(movingright)
transform.Translate(Vector3.right * amtToMove);

if(movingleft)// this is for moving left
if(transform.position.x < targetApositionx)//if it reaches the A position then stop moving left, activate right moving but deactivate move to make the rotation first
{
movingleft = false;
movingright = true;
moving = false;
rotating = true;
}
//same logic but to the right
if(movingright)
if(transform.position.x > targetBpositionx)
{
movingright = false;
movingleft = true;
moving = false;
rotating = true;
}
}

if(rotating)
{
here you need to make something similar, define the rotation range, or how many degrees the object will rotate before moving again, after the rotation is complete, then activate moving and deactivate rotating
}

please first you need to get the logic, then use the logic to javascript

hope this is of any help

Vector3.MoveTowards

Use that in a transform.translate() call for perfect raycasted movement.