You can check the distance in a condition to so Invoke something. (eg) Delay and return function. Instead of swapping the positions on the way back you may want to try -Time.time
I think using an animation would be a nice and easy way to do it.
function Start() {
var curve:AnimationCurve = new AnimationCurve();
curve.AddKey(0,0);
curve.AddKey(1,5);
curve.AddKey(2,0);
var clip:AnimationClip = new AnimationClip();
clip.SetCurve("",Transform,"localPosition.x",curve);
clip.wrapMode = WrapMode.Loop;
animation.AddClip(clip,"clipName");
animation.Play("clipName");
}
@script RequireComponent(Animation)
I’m not really sure how you want it, but in general you can define the path by adding keys with AddKey(time, value) to the curve.
The curve is then added to the animation in combination with a variable (in my example localPosition.x). As long as the animation is playing, this variable will change its value according to the key values defined in the curve.
Also, if you don’t want to do it programmatically, you can achieve the same thing by using the Animation Viewer. Furthermore there you get a visualization of the curves and a list of all values which can be changed. So at least its a good thing to get an understanding of how animations work.