- Home /
 
C# Mathf.PingPong Rotate Back and Forth
I've been trying to get my gameobject to rotate back and forth using Mathf.PingPong. It only goes from origin to rotFl. I need it to go from origin to rotFl then switch to from origin to -rotFl. Any ideas for what I should put in the if statement so that the switch occurs? I'm thinking it's something like if it retreats back to origin but I'm not sure.
     public float rotFl;
     // Use this for initialization
     void Start () {
     
     }
     
     // Update is called once per frame
     void Update () {
         transform.localEulerAngles = new Vector3(0, 0, Mathf.PingPong(Time.time * 50, rotFl));
         /*if( check something so that switch occurs){
         transform.localEulerAngles = new Vector3(0, 0, Mathf.PingPong(Time.time * 50, -rotFl));    
         }*/
     }
 
              Answer by allenallenallen · Aug 12, 2015 at 07:39 AM
Read this:
http://docs.unity3d.com/ScriptReference/Mathf.PingPong.html
PingPong only makes the value from 0 to length, never negative.
So in order to do what you need, you put a negative right in front of Mathf.PingPong()
 transform.localEulerAngles = new Vector3(0, 0, -Mathf.PingPong(Time.time * 50, rotFl)); 
 
 
              Answer by Mefisto27 · May 29, 2020 at 09:54 AM
Firstly you should not modify directly eular angels use Quaternion instead. My code sample uses y direction to rotate
  transform.rotation = Quaternion.Euler(defaultRot.x,Mathf.PingPong(Time.time * speed, rotFL*2)-rotFL, defaultRot.z);
 
                    private void Awake()
     {
         speed=50;
         defaultRot = rotation.eulerAngles;
     }
 
 
 
              Your answer
 
             Follow this Question
Related Questions
Translate from JS to C# localEulerAngles 1 Answer
Distribute terrain in zones 3 Answers
Maintaining direction while jumping / rotating 3 Answers
Arm rotation question 1 Answer
Mathf.PingPong strange behaviour 1 Answer