For loop timing vs FP.elapsed [Solved]


(Lozza JP) #1

Me again, trying to get something to happen after ~1 second in a for loop. If I put in my for loop incrementer parameter counter += FP.elapsed, I found it counting in an instant, I imagine because for loop is called very quickly over and over. If I try to use a counter as a global varial and have it updating in update() I find it is not updating during the for loop and is stuck at 0, causing an infinite loop. Here is my code

		if (counter > time && !thisIsBack) disappear();
		
		if (counter > time && thisIsBack)
		{
			disappear();
			reappear();
		}
		
		if (inReappear)
		{
			counter += FP.elapsed;
		}
		
	} // End update function
	
	private function disappear():void
	{
		// Add some effect of removal here. puff of smoke or something? unless covered in final sprite
		FP.world.remove(this);
	} // End disappear function
	
	private function reappear():void
	{
		inReappear = true;
		var quickBool = true;
		counter = 0;
		for (; counter < 1.5; )
		{
			trace(counter);
			if (counter > 1 && quickBool)
			{
				// var newAgain = new DisappearingBlock(x, y, width, thisAssetSprite, time, thisIsBack);
				// world.add(newAgain);
				trace("time");
			}
			if (counter > 1)
			{
				quickBool = false;
				inReappear = false;
			}
		}
		
	}

(Lozza JP) #2

Figured it out.

When the for loop runs, the entire loop runs before going back into the update method so counter += FP.elapsed happens.

You can use break; to get out of the loop at the end of each iteration and the loop will only execute for the amount of frames you want.


(Jacob Albano) #3

Breaking out of the loop after the first iteration just means it runs once. The next frame it will start right over again at the beginning. You might as well not have a loop at all. :wink:

This is a common mistake to make, but for and while loops have no knowledge of Flashpunk frames. If you like, you can think of update() as a function that gets called in a big giant while (gameRunning) loop, but don’t expect multiple iterations of any other loop to be processed over multiple frames.


(Lozza JP) #4

And update runs at around 60 times a second? (once per frame) correct?

I actually refactored this in some way that works, i think using a while loop, and the counter iterates up still.

So the while loop is technically breaking every frame as you say but it is doing the required behaviour.

will a counter += FP.elapsed; In update section take 1 second for counter to = ~1?


(Jacob Albano) #5

Yes, it will. You don’t need to surround it with a loop of any sort for that.


(Lozza JP) #6

So my while counter < 1 Might as well just be if counter < 1… -_-

So I guess loops are just useful for iterating actual values like an array index where the counter is in the loop.

Was that a yes to the 1 second question?


(Jacob Albano) #7

Yes to both questions.