Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Join us on Dec 8, 2022, between 7 am & 7 pm EST, in the DOTS Dev Blitz Day 2022 - Q&A forum, Discord, and Unity3D Subreddit to learn more about DOTS directly from the Unity Developers.
    Dismiss Notice
  3. Have a look at our Games Focus blog post series which will show what Unity is doing for all game developers – now, next year, and in the future.
    Dismiss Notice

Mathf.Repeat vs Mathf.PingPong

Discussion in 'Scripting' started by madcalf, Feb 23, 2006.

  1. madcalf

    madcalf

    Joined:
    Jan 12, 2006
    Posts:
    56
    Could someone please explain what exactly Mathf.Repeat and Mathf.PingPong do in a bit more detail than the docs? I'm just not quite getting it.

    thanx!
    d
     
  2. freyr

    freyr

    Joined:
    Apr 7, 2005
    Posts:
    1,148
    Repeat is the same as the modulo operator. (Which btw. does work with floats.)

    Repeat(t, length) works a bit like this (for positive t):

    Code (csharp):
    1.  
    2.    if t is less than length, return t unmodified.
    3.    if t is greater than length, subtract length from t until t is less than length
    4.  
    Example:
    Code (csharp):
    1.  
    2.    // Will print 0,1,2,0,1,2,0,1,2
    3.    foreach( var t in [0,1,2,3,4,5,6,7,8]) {
    4.        print(Mathf.Repeat(t, 3));
    5.    }
    6.  
    PingPong will reverse the interval on every second repeat.
    Code (csharp):
    1.  
    2.    // Will print 0,1,2,3,2,1,0,1,2
    3.    foreach( var t in [0,1,2,3,4,5,6,7,8]) {
    4.        print(Mathf.PingPong(t, 3));
    5.    }
    6.  
    PingPong could actually be implemented using Repeat like this:
    Code (csharp):
    1.  
    2.     function MyPingPong(t, length) {
    3.         var result=Mathf.Repeat(t, length*2);
    4.         if( result > length)
    5.              result = (2*length) - result;
    6.         return result;
    7.     }
    8.  
     
  3. madcalf

    madcalf

    Joined:
    Jan 12, 2006
    Posts:
    56
    Thanx for that exlpanation. Now I understand the .mov texture animation script i've been using.

    Still not so sure I understand Mathf.PingPong or what you'd use that for, though.

    thanx again!
    d
     
  4. freyr

    freyr

    Joined:
    Apr 7, 2005
    Posts:
    1,148
    If you used Repeat in the mov script to loop an animation, using PingPong would let it play backwards and forwards instead.
     
  5. madcalf

    madcalf

    Joined:
    Jan 12, 2006
    Posts:
    56
    Oh, i get it! Really had to hit me over the head with that one! That's really cool to have a built-in function that does that.