Rotate enemy with Mathf.PingPong

Hi Everyone!

I’m creating a 2D platformer with round enemies in it.
I want those enemies to move back and forth on x-axis. Mathf.PingPong works for that perectly, but i also want to rotate them on z-axis so it looks like they are rolling on the ground back and forth, but i’m doing something wrong.
The enemy is parented to an empty gameobject so i can adjust it’s local position.

Here’s the code:

  function Update () 
{
  transform.localPosition.x = Mathf.PingPong(Time.time, Dist);
  transform.localRotation.z = Mathf.PingPong(Time.time, Rot);
  }

However the rotation stops when it reaches 180degree. Tried with Rotation instead localRotation but it didn’t work.
Can someone give me a tip how to make it right?
Thank You!

If you are careful, you can use eulerAngles to do the rotation you are looking for. Rather than a separate PingPong() for rotation, you will have better results if you use the same value. That way the rotation direction will match the move direction:

pragma strict
 
var dist = 5.0;
var moveSpeed = 1.0;
var rot = 90.0;
 
private var v = Vector3.zero;
  
function Update () 
{
    var x = Mathf.PingPong(moveSpeed * Time.time, dist);
    //var x = (Mathf.Sin(moveSpeed * Time.time) + 1.0) / 2.0 * dist;
    transform.localPosition.x = x;
    v.z = rot * -x;
    transform.eulerAngles = v;
}

The commented out line is an alternate way of doing the ‘ping pong’ of the value that produces a results that feels more realistic. Also look at the following answer for more information about assigning values to the components of transform.rotation: