- Home /
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?
Answer by Bunny83 · Oct 10, 2016 at 09:45 PM
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.
thanks, playing with it a bit but looks like it's doing the job well, thanks :)
umm, also trying to separate the time for x and y axes, I'm assu$$anonymous$$g you can have 2 different t variables but not quite sure how to use them in the end result... feels like it shouldn't be that difficult :X
Why would you seperate the movement on the x and y axis? This would result in a more or less chaotic movement since when the two motions aren't synchronised you would move anywhere inside the rectangle between your $$anonymous$$ and max x / y values. The movement would be like a bouncing ball that is reflected on the border of that rectangle.
If you really want to do this you can't use Lerp. Lerp is a linear interpolation. So you have two points and you go from one to the other in a straight line (linear). So you would need to use the other approach where you move on each axis seperately.
Your answer
Follow this Question
Related Questions
Help with Mathf.PingPong 2 Answers
Does Mathf.PingPong always have to start at (0,0,0)? 1 Answer
How to rotate object back and forth on input hold? 1 Answer
Mathf function on GetKey 1 Answer