Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Unity's Mathf.PingPong actually do?

Tags:

c#

unity3d

The Unity Docs for Mathf.PingPong says:

PingPongs the value t, so that it is never larger than length and never smaller than 0.

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?

like image 571
Pipupnipup Avatar asked Jan 01 '23 03:01

Pipupnipup


1 Answers

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
enter image description here
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
enter image description here
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);
like image 71
Jay Avatar answered Jan 17 '23 09:01

Jay