line is that it will only call when your object is actually more than 4 away from the origin. That is to say, it will have your object move out to a distance of 4, and then stop moving.
What you should do instead, is have something like this:
This will make your object bounce inbetween (maxDist, 0, 0) and (minDist, 0, 0). maxDist and minDist are assigned in the editor if you want to change it at runtime!
Of course, I would prefer to control the cube's position using Vector3.Lerp() or related interpolation functions- possibly defining multiple waypoints via an array of transforms, but that would be the answer to a different question.
function Update()
{
// Set the x position to oscillate between -4 and 4
transform.position.x = Mathf.Sin(Time.deltaTime) * 4;
}
If you want to speed up or slow down the oscillation you can use a weight in the calculation:
function Update()
{
var OscillationWeight = 1.0;
// Set the x position to oscillate between -4 and 4
transform.position.x = Mathf.Sin(Time.deltaTime * OscillationWeight) * 4;
}
Simply increase “OscillationWeight” to speed it up or decrease it to slow down.