Can you reset a timer using millis()?

edited December 2016 in Questions about Code

Hello, I am new to Processing, so I may not understand things that may seem clear to experiences Processing users. I have trouble in resetting a timer : time = millis()/1000;. I have tried using an if statement ( in the next comment), but I think it starts from the beginning of the program.

Can anyone help?

Answers

  • edited December 2016
                    if (level == 1) {
                      dX = dX + 2;
                      time1 = millis()/1000;
                      time = time1;
                    }
                      if (level == 2) {
                        dX = dX + 3;    
                        time2 = millis()/1000;
                        time = time2;
                      }
    
                      if (level == 3) {
                        dX = dX + 3.5;
                        time3 = millis()/1000;
                        time = time3;
                      }
    
  • dX is the position of a horizontally moving image to the right, and by each level, the speed increases. Please point out my mistakes or improvements if I have any.

  • Can you post all your code? We need to be able to execute it to see what is your approach.

    Kf

  • millis() is always equal to time since the beginning of the sketch starting. Look at these statements from your code:

    time1 = millis()/1000;
    time2 = millis()/1000;
    time3 = millis()/1000;
    

    In every case, you are doing the same thing -- setting a variable to the number of milliseconds since the sketch started. This is why your if statements have no effect.

    You need a pattern more like this (depending on the kind of timer you want, how you want to control it, whether start times or stop time or both are important, etc. etc.):

    float start, runtime;
    
    void setup(){
      start = millis();
    }
    
    void draw(){
      background(0);
      // how long has the sketch been running? millis
      text((float)millis()/1000, 10,height/6);
    
      // when was the timer last started? saved millis variable
      text(start/1000, 10,height/3);
    
      // how long has the timer been running? current millis - saved millis
      runtime = millis() - start;
      text(runtime/1000, 10,height/2);
    }
    
    void keyPressed(){
      // mark a new timer start time
      start = millis();
    }
    
  • Thanks @jeremydouglass!!!! :)

    I'm so happy now, thanks to everyone who helped me! :3 SC

Sign In or Register to comment.