Moving an object left and right

Hi all, I’m trying to get an object to move left to a certain point and then once it reaches that point it moves right until a certain point.

I’ve got the object to move left, but can’t get it to move right as it seems to freeze once it’s reached the position I want.

void Update ()
{

    transform.Translate(Vector3.left * speed * Time.deltaTime);

    if (transform.position.x <= -4)
    {
        transform.Translate(Vector3.right * speed * Time.deltaTime);
        Debug.Log("Working!");
    }

The object goes left, and reaches to -4 on the x Axis but then freezes and doesn’t move, any ideas?

Thanks!

The issue here is that, when you do reach -4, you nudge it to the right and then you’re no longer <= -4 so you’re not moving right anymore. Not to mention, you’re nudging it to the left all the time, and then sometimes nudging it right as well. A nudge left followed by an equal nudge right is essentially just not moving at all. What you need is to only translate in one direction at a time, and to have that direction persist and only change when necessary. Something like this.

//Up at the top with your variables:
private Vector3 dir = Vector3.left;

//Your Update function
void Update(){
     transform.Translate(dir*speed*Time.deltaTime);

     if(transform.position.x <= -4){
          dir = Vector3.right;
     }else if(transform.position.x >= 4){
          dir = Vector3.left;
     }
}

The important things to note here are:

  • The direction persists between frames. It only changes in very specific cases
  • It’s generally a good idea to only do 1 translate call per frame and store your direction in a variable anyway. Explicitly setting the direction and speed is much more predictable and you always know why something moves the way it does.
  • I’m assuming you wanted it going from -4 to 4, although really you should store these in variables. Firstly, you can see these in the inspector, but secondly, the numbers -4 and 4 on their own don’t mean anything on their own. On the other hand, ‘leftExtent’ and ‘rightExtent’ might be -4 and 4, but are much more meaningful and, if you use these extents for other things, you don’t have to change these magic numbers everywhere.

Think how this method works, step by step:

  1. move the object left

  2. check if reached the target on the left

  3. if yes, then move the object right

So, when your object reaches the target spot on the left, you’re moving it both left and right at the same time, in result not moving it at all.

Add a flag to check whether you’re still moving left or right, then based on its value move in the direction you want:

private bool movingLeft;
void Start() {
    movingLeft = true;
}
void Update() {
    if (movingLeft == true) {
        // move left
        if (transform.position.x <= -4) movingLeft = false;
    } else {
        // move right
    }
}