using Mathf.PingPong

trying to move a 2d sprite using Mathf.PingPong, could be a stupid question, just wondering how to go about it when the starting position is lower than the target position.
Example is if I want a trap to start at 9 on the y-axis and go to 6 on the y-axis, the code would be like this:

rb2D.MovePosition(Vector2(rb2D.position.x, Mathf.PingPong(Time.time * speed, startPos.y-targetPos.y) + targetPos.y));

but if I want it to start at 6 and go to 9 then not sure how to make this work?

So you just want a general solution for both cases? The easiest way is to use Lerp as well as PingPong. However when using lerp the speed becomes distance dependent as the time to reach the target is always the same. You can however correct it by the distance between start and end:

// UnityScript / C#
var dif = targetPos - startPos;
var t = Mathf.PingPong(Time.time * speed / dif.magnitude, 1f);
rb2D.MovePosition(Vector2.Lerp(startPos, targetPos, t));

Another way would be to take the absolute difference which you use inside the pingpong and in addition use the sign of the difference to move in the correct direction.

// UnityScript
var dif = targetPos - startPos;
var s = Mathf.Sign(dif.y);
rb2D.MovePosition(Vector2(rb2D.position.x, startPos.y + Mathf.PingPong(Time.time * speed, dif.y*s)*s));

Here dif.y*s is simply the absolute value. So if it’s “-7” it will be “7” since (-7)*(-1) --> 7. So the pingpong is done in the positive range and we simply multiply the result again by “s” to get either a negative or positive offset depending on the direction.

The first Lerp version however is much easier and also works in any direction, not just the y axis.