- Home /
Int Based PingPong or oscillation without using Mathf.Pingpong?
(int)start+Mathf.PingPong(Time.time, end)
something similar to this without casting float to int. but use an int oscillation instead is their a direct approach to this
I don't know why you are trying to avoid the cast, but I believe the result you are looking for is something that counts up to some end and then back down to 0 at a fixed rate. A few lines in a co-routine or a function called by InvokeRepeating() might work.
thank you for your suggestion here is actually what i did :) how stupid of me... if(i<=end && CountUp==true){ i++; if(i==end){ CountUp=false; } }if(i>=start && CountUp==false){ i--; if(i==start){ CountUp=true; } }
if their is a much simplier version of it i would be glad to know
Not necessarily better, but I would have oscillated the value that is being added or subtracted.
#pragma strict
private var val = 0;
private var dir = 1;
var period = 1.0;
var end = 5;
function Start() {
InvokeRepeating("PingPongInt", period, period);
}
function PingPongInt() {
val += dir;
if (val == 0) dir = 1;
if (val == end) dir = -1;
}
Answer by cariaga · Feb 16, 2014 at 05:43 PM
if(i<=end && CountUp==true){
i++;
if(i==end){
CountUp=false;
}
}
if(i>=start && CountUp==false){
i--; if(i==start){
CountUp=true;
}
}
well it worked on my specific goal :) robertbu answer is also good
Answer by Anderson-Cardoso859 · Nov 20, 2016 at 09:56 AM
public static int PingPong(int t, int length)
{
int q = t / length;
int r = t % length;
if ((q % 2) == 0)
return r;
else
return length - r;
}
It would be easier to simply use double the length, do a single modulo and a conditional return value for the first half and one for the second half.
int r = t % (2*length);
if (r < length)
return r;
else
return length*2 - r;
Though your solution does work as well. so +1.
Note for potential users of this method: The range of the returned values will be 0 - length inclusive. So PingPong(xxx, 5)
will generate the sequence:
0 1 2 3 4 5 4 3 2 1 0 1 2 3 4 5 4 3 2 1 0 ...
So it effectively "swings" over 6 values. I'm just adding this as most int-based methods have the max value exclusive like Random.Range for example.
Your answer
Follow this Question
Related Questions
Help with Mathf.PingPong 2 Answers
How to rotate object back and forth on input hold? 1 Answer
Does Mathf.PingPong always have to start at (0,0,0)? 1 Answer
Mathf function on GetKey 1 Answer