How to add +1 to variable every 10 seconds in Processing?

前端 未结 3 1444
日久生厌
日久生厌 2020-12-07 05:41

Excuse my ignorance, but I ran into a problem that turned out to be challenging for my current knowledge in programming with Processing, even though the idea is quite simple

相关标签:
3条回答
  • 2020-12-07 06:14

    You could store the last number of seconds in a static (or global) variable, and only increment i when the current number of seconds is higher than the oldsecs

    void draw() {
        static int oldsecs = 0;
        int secs = millis() / 1000;
        if (secs > oldsecs) {
            i++;
            oldsecs = secs;
        }
        ...
    

    Assuming the language is C, and the int type is not overflowed by the number of seconds.

    0 讨论(0)
  • 2020-12-07 06:31

    The other answers are fine general approaches, but they don't take advantage of the features that Processing provides for you.

    For example, you could use the frameCount variable to check how many frames have elapsed. Since draw() is called 60 times per second, 10 seconds is 600 frames. Something like this:

    void draw(){
      if(frameCount % 600 == 0){
        // 10 seconds has elapsed
      }
    }
    

    Another way to do this is to store the last time 10 seconds elapsed, and then check that against the current time to see if 10 seconds has elapsed since then. Something like this:

    int previousTime = 0;
    
    void draw(){
       if(millis() > previousTime + 10*1000){
          // 10 seconds has elapsed
          previousTime = millis();
       }
    }
    

    More info can be found in the reference.

    0 讨论(0)
  • 2020-12-07 06:40

    Ringo has a solution that's perfectly fine.

    Another way you can do this easily is:

    bool addOnce = false;
    void draw()
    {
      int time = (millis() % 10000) / 1000;
      if (time == 9)
      {
          if(!addOnce) {
              addOnce = true;
              i++;
          }
      } else { addOnce = false; }
    }
    

    As long as time == 9, we'll only get through if(!addOnce) one time.

    After it changes, we reset the flag.

    0 讨论(0)
提交回复
热议问题