Skip to main content
BuggyBungo
New Participant
June 20, 2022
Question

How do you make a loop that subtracts 1 to a variable each frame?

  • June 20, 2022
  • 2 replies
  • 534 views

Hello!  I am pretty new to AE expressions so I apologize for my behavior if it is inconvenient. 

 

I currently have this,

if (k != y) {
      k = k - time
}


I wish to make it so k decreases by 1 every frame once it is not y; however, the time variable not does account for when k is not y and does not decrease it by 1 each frame.

Any tips?  Should I be utilizing things such as "while"?  I have noticed Javascript does not have any sleep/wait/delay functions and was wondering if AE had any of those.

This topic has been closed for replies.

2 replies

Mylenium
Brainiac
June 20, 2022

AE cannot6 store persistent data in expressions. An expression always evaluates fully for every frame, so if a loop has 5000 cycles before a condition is met, it will go through those 5000 loops even if the result has already been calculated on the previous frame. That's just how it is. You need to make sure al lthe calculations happen inside your loop and yes, that means using while() or for() loops and things such as valueAtTime() to look at results at different times. Otherwise I'm not sure what your simplistic loop would even achieve other than always returning the same result for every frame. You may want to wish to study other people's expression examples to get a grasp what this stuff can do and how it works such as Dan Ebberts' classics at motionscript.com.

 

Mylenium

BuggyBungo
New Participant
June 20, 2022

Made a mistake

(however, the time variable doesn't* account for when k is not y and does not decrease it by 1 each frame.)

Dan Ebberts
Community Expert
June 20, 2022

As Mylenium points out, expressions don't have persistent data. But you shouldn't need that in your case. You can use timeToFrames(time) to get how many frames have elapsed, and you can subtract that from whatever starting value you want to give you a value that decreases by one each frame.

BuggyBungo
New Participant
June 20, 2022

Hello!  Thank you for the response!

 

While I looked into the timeToFrames function, and forgive my lack of understanding, wouldn't the function not subtract one every frame once it is called again as it relies on the time variable?

 

Also for more context, the y is a health bar (controlled by a slider) and k is a second health bar that displays poison damage. When the y slides down, the poison damage bar is shown in a layer below. The poison damage stops when it reaches the same number as the health bar; it starts again whenever the health bar lowers again.
I hope that gives more of a picture.

 

if (k != y) {
    // this is where I want it to subtract 1 to k, every frame
}
if (k <= y){
    k=y
}