1

I have a Cube on (0,2,0) and I want it to move on the y axis from 2 down to 1 and then up to 3 back to 1 back to 3 and so on...

Can someone explain me, what to pass in as parameters when using Mathf.PingPong()?

I have

public virtual void PingPongCollectable(Transform transform, float speed)
{
    Vector3 pos = transform.position; // current position
    pos.y = Mathf.PingPong( ? , ? ); // missing parameters, calculate new position on y
    transform.position = pos; // new position
}

so where do I have to pass in the speed and the coordinates A (above) and B (below) ?

The cube should just smoothly slide up and down in a loop.

Thanks!

Question3r
  • 2,166
  • 19
  • 100
  • 200

1 Answers1

0

The signature of the Mathf.PingPong method is the following one :

public static float PingPong(float t, float length);

PingPongs the value t, so that it is never larger than length and never smaller than 0.
The returned value will move back and forth between 0 and length.

The first parameter should be Time.time if you want a smooth transition.
The second parameter is the max value. The method then gives you a position between 0 and that max value.
You can then set a bottom floor and a length for the ping-pong method.

Here is an example using the code you provided :

public virtual void PingPongCollectable(Transform transform, float speed)
{
    Vector3 pos = transform.position;
    float length = 1.0f; // Desired length of the ping-pong
    float bottomFloor = 1.5f; // The low position of the ping-pong
    pos.y = Mathf.PingPong(Time.time,  length) + bottomFloor;
    transform.position = pos; // new position
}

Source : https://docs.unity3d.com/ScriptReference/Mathf.PingPong.html

CBinet
  • 187
  • 2
  • 12
  • using `Mathf.PingPong(Time.deltaTime, length - bottomFloor) + bottomFloor` is not correct. the cube instantly jumps to 0 and moves to 3 and back to 0. but it should move from 1.5f to 2.5f. – Question3r Jun 30 '17 at 18:12
  • I edited my example. If you want to move between 1.5f and 2.5f, you can do this : `Mathf.PingPong(Time.deltaTime, 1.0f) + 1.5f` – CBinet Jun 30 '17 at 19:28
  • You need to use `Time.time` as in the example in the docs, or accumulate the time in a member variable. `Time.deltaTime` will generally not increase over time so you'll get the same position frame after frame. – BMac Jun 30 '17 at 20:23