Need assistance with timing! [millis()]

Hey! Thanks for coming to help me out. Today I’m completely stumped on how to get a timer mechanism to work. I’m making a clicker type game and I cant figure out how to add money every second.

my goal is this:

for each 1000 milliseconds add x to total

I have no idea how to check to see if its been 1000 milliseconds. I’m assuming you have to do some subtraction and stuff but I don’t know what order of operations to use.

i tried assigning millis() to a variable and trying out a few math formulas, but nothing is working out for me. I’m sure the solution is super simple, but I am absolutely stumped. Doesn’t help that all the code on other forum posts makes no sense to me/has no notes lol

1 Like

Hello,

Show us what you have done so far.

I don’t have much for it. I didn’t really know where to even start.

my best guess was this:

int ms;
float moneyTotal;
float idleMoney = 1;

void draw(){
   CPS();
}
void CPS(){
   ms = millis();
   if(ms >= 1000){
      moneyTotal += idleMoney;
      ms = 0;
   }
}

that doesn’t work unfortunately, and I tried a few other things but still to no avail.

1 Like

I provided a simple example:

int whattimeisitnow;
int whattimeisitatstartofstopwatch;
int timepassedtoresetstopwatch = 1000;

//setup runs once
void setup()
  {
  whattimeisitatstartofstopwatch = millis();  
  }

//draw loops 60 frames per sec  
void draw()
  {
  whattimeisitnow = millis();
  if (whattimeisitnow > whattimeisitatstartofstopwatch + timepassedtoresetstopwatch)  
    {
    println("1000 ms have passed!");
    whattimeisitatstartofstopwatch = millis();                     //reset stopwatch and start over
    }
  }

This is a very basic timer that is very common; I just added descriptive variable names.

I would like you to explain to me how it works and then try writing it from scratch.
I do this often (code from scratch) as an exercise to work my brain.

You can also add println() statements to see what is going on with code.
Keep in mind that millis() is constantly updating in the background with the passage of time and the variables will update.

https://processing.org/reference/millis_.html

:)

2 Likes

this will work perfectly! thanks!