- Home /
Make value change to anoter over time and back loop
Hello. How could I make a value to go from -1 to 1, then from 1 to -1 and back again. It should be a infinite loop. And every step (from -1 to 1 or from 1 to -1) should be happening over a given time? Thank you!
Answer by robertbu · Oct 04, 2013 at 08:00 PM
You can use Mathf.PingPong() or Mathf.Sin() in Update():
var val = Mathf.PingPong(Time.time * speed, 2.0) - 1.0;
or:
var val = Mathf.Sin(time.time * speed);
Mathf.Sin() will give a sinusoidal change between -1.0 and 1.0;
Seeing @HanClinto's answer, I don't know if you want just -1 and 1, or all fractional values in between.
I guess I assumed he wanted integers, but after seeing your answer, maybe he wanted the fractional values? :)
Nice clean answers, btw.
Answer by HanClinto · Oct 04, 2013 at 08:01 PM
The way I do this is the following (taken from a Pac Man game I'm working on where the sprites cycle in a back-and-forth munching loop):
// Set animation frame
const int NUM_FRAMES = 4; // In our Pac Man animation, we have 4 frames.
//We want the frames to go 0,1,2,3,2,1 and repeat.
const float ANIM_SPEED = 0.4f; // Modify this parameter to determine the speed at which the frames progress
int frame = ((int) (this.transform.x * ANIM_SPEED)) % NUM_FRAMES;
if (frame > NUM_FRAMES * 0.5)
frame = NUM_FRAMES - frame;
// "frame" will now cycle from 0 to 3 and back again in reverse according to the "x" of the transform.
Edit: So in your case, you have 4 desired values. -1, 0, 1, 0, then repeat. For that, you can do:
int counter = 0;
void Update() {
counter++; // I assume this is going up in some fashion
int ticktock = (counter % 4); // ticktock is now 0 to 3
if (ticktock > 2)
ticktock = 1; // ticktock is now 0 to 2
ticktock--; //ticktock is now -1 to 1
}
Another way is to use an array to store the values you want to toggle through. This is perhaps one of the easier ways to understand:
int counter = 0;
void Update() {
const int[] values = {-1, 0, 1, -1}
int ticktock = values[(counter++) % 4];
// ticktock is now at the desired value
}
Answer by YoungDeveloper · Oct 04, 2013 at 08:08 PM
Wait stuff is different depending on are you using c# or unity script.
int a = 1;
for(;;){
//infinite loop
// if unity script use yield waitforseconds any function, if c#create new IEnumerator function, copy the for loop the
//re because only in that function you can use yield waiforsecobds
//start coroutine from start or whatever
a *= -1;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613115324im_/https://answers.unity.com/themes/thub/images/avi.jpg)