The Unity Docs for Mathf.PingPong says:
PingPongs the value
t
, so that it is never larger thanlength
and never smaller than0
.
I get that it's rotating a value between 0 and length
, what I don't get is what is the value t
doing and how does it relate to how PingPong works?
If I set t
to any constant, I always get that value back
void Update()
{
// always prints: 1
print(Mathf.PingPong(1f, 1f));
// always prints 0
print(Mathf.PingPong(0f, 1f));
}
Every time I see PingPong used in examples it has Time.time
used for the t
value (or some maths based on Time.time
). Why?
The only explanation I've seen was from this question: c# Unity Mathf.PingPong not working which implies that the value of t
must always be changing, but again it's not clear why or what's going on.
So, what is Mathf.PingPong
actually doing with t
/ what is the value t
actually for, and how do you use the function properly?
So Mathf.PingPong()
uses a function calls Mathf.Repeat()
These are likely intended as tweening/easing helper functions
So Mathf.Repeat(float t, float length)
will create a graph like this
Where length
is the length of each line segment, and t
is the X value of the function (the return value being the corresponding Y position on the graph)
What Mathf.PingPong(float t, float length)
does looks more like this
Again where length
describes the height of each triangle and t
gives the X position
A common use case for this is we want some value to change along with this graph, as in walking along it with a steadily increasing X value, and take the value of Y at each step.
The easiest way to do this is to pass Time.time
in as the t
argument, which will get the value of this function at the corresponding X position.
float Y = Mathf.PingPong(Time.time,Max_Y_Value);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With