- Home /
Mathf.PingPong strange behaviour
I applied to some objects the Mathf.PingPong function. I followed the Script Reference indications but the objects behave in a strange way: when the Mathf.PingPong function starts (at a certain time) they move very rapidly towards the positive x axis. I don't know where they are going and if they are going to come back. It doesn't seem so.
This is the code:
function Update (){
if (Time.time > 3){
transform.position = transform.position + Vector3(Mathf.PingPong(Time.time, 3), 0, Mathf.PingPong(Time.time, 2));
}
}
Where's the mistake?
Answer by Owen-Reynolds · Jul 14, 2012 at 04:22 PM
Try something simple, like: transform.position = Vector3(Mathf.PingPong(Time.time, 3),0,0);`. To speed it up, use Time.time*2
.
The problem is that you're adding to position. If you add 1 to x every frame, clearly the object will shoot to the right. If you add Random.Range(0,3)
then the object will move left in a jerky fashion (it goes 0, 1 or 2 each frame.)
PingPong(time, 3)
is just a number between 0 and 3, based on the current seconds. If you add that to your x-position, of course you go right -- slow, then fast, then slow.
if i use the code:
transform.position = Vector3($$anonymous$$athf.PingPong(Time.time, 3),0,0);
the objects rapidly jump at 0,0,0 and then they start moving normally from 0 to 3 and back. $$anonymous$$y problem is: How can i make the objects start moving from their actual position, without being moved to 0,0,0 first?
Ping-pong "from anywhere" is tricky to use, but there are a few answers here you can look at. The trick is that Time.time
is the time from the_start of the game_. Ins$$anonymous$$d, you have to save when you start ping-ponging, and find the seconds from there.
Or, sometimes easier just to use regular math to make your x
go up to 3, down to 0 ... and keep the others the same. If you aren't sure how to do that, there's lots of advice here about how to learn program$$anonymous$$g for Unity.
i tried to use a time value, ins$$anonymous$$d of Time.time, that starts from the ping pong movement beginning. The result is that all the objects jump to a single point in spaace and start moving all togheter