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.