# How to keep an object that moves back and forth from changing its travel time.

So in my game I have a GameObject that repeatedly moves back and forth in the scene. This is the code I am using

``````if (isMoving)
{
//move the object
if (isMovingRight)
{
transform.position += Vector3.right * Time.deltaTime * speed;
if (transform.position.x >= _playAreaWidth)
{
isMovingRight = false;
}
}
else
{
transform.position += -Vector3.right * Time.deltaTime * speed;
if (transform.position.x <= -_playAreaWidth)
{
isMovingRight = true;
}
}
}
``````

Now the problem is that when I input the speed value and the _playAreaWidth value I should be able to predict exactly how long it will take my object to go from one end to the other, however, because in the span of one frame it can slightly overshoot _playAreaWidth there is a very slight variation to the time it takes. Over time this slight variation de-synchronizes the objects movement with the soundtrack. For the life of me I canâ€™t figure out how to get around this, any help would be welcome.

Hopefully this will do the trick. Basically what you need to do is find out how far you overshot the target, then take that distance back off, simulating a bounce mid-frame.

``````using UnityEngine;
using System.Collections;

public class MoveBackAndForth : MonoBehaviour
{
public bool isMoving;
public bool isMovingRight;
public float speed = 5f;
public float _playAreaWidth = 5f;

Vector3 targetPos;

void Start()
{
targetPos = transform.position;
}

void Update()
{
if (isMoving)
{
if (isMovingRight)
{
targetPos.x += Time.deltaTime * speed;
if (targetPos.x >= _playAreaWidth)
{
isMovingRight = false;
//If we've gone too far, get the distance past the edge (targetPos.x - _playAreaWidth), then take that from _playAreaWidth
//This will loop us around without over/under shooting the target and hopefully keep us in sync.
targetPos.x = _playAreaWidth - (targetPos.x - _playAreaWidth);
}
}
else
{
targetPos.x -= Time.deltaTime * speed;
if (targetPos.x <= -_playAreaWidth)
{
isMovingRight = true;
targetPos.x = -_playAreaWidth - (targetPos.x + _playAreaWidth);
}
}
transform.position = targetPos;
}
}
}
``````