Timer and ticks and should I be shot?

I’m posting this here because it’s stupid and I should know better considering this is what I was doing back in my 10th grade, hence I need to be shot for stupidity.

Does this code do 30 ticks per second?


int ticks = 30;
            long start = System.nanoTime();
            //do logic
            if(end >= (1e-9/60) && ticksDone <= ticks){
                  logicLoop(clickLoc, mouseLoc, playerCamera);
                  ticksDone++;
            }
            if(ticksDone == 30)
                  ticksDone = 0;
            end = System.nanoTime() - start;

I’ve corrected it to this:


int ticks = 60;
            long start = System.nanoTime();
            double time = 30 / Math.pow((1e-9/1)*10, 9);
            
            if(end <= time && ticksDone <= ticks){
                  logicLoop(clickLoc, mouseLoc, playerCamera);
                  ticksDone++;
            }
            
            if(ticksDone == 30)
                  ticksDone = 0;
            
            end = System.nanoTime() - start;

I’m a bit confused. Is this in a loop? I ran it like such anyway, and it doesn’t seem to be a controlled loop. It will just call logicLoop() as much as it can, rather than 30 times a second (so I’m guessing I’m doing something wrong).

Sorry if I’m misunderstanding you, if I am, can you be a little clearer of what you want it to do?

Loop 30 times a second.

This is the loop I’m currently using:

long nextCheck = System.nanoTime() + 1000000000;
int      fpsCount = 0;
int      fps      = 0;

while(true)
{
      nanoTime = System.nanoTime();

      if(nanoTime      >= nextCheck)
      {
            nextCheck =      nanoTime + 1000000000;
            fps      = fpsCount;
            fpsCount = 0;
      }

      fpsCount++;

      tick();      // do stuff      here

      while(System.nanoTime()      < nanoTime + (1000000000 / targetFPS))
      {
            Thread.yield();
      }
}

Where targetFPS would be 30 :slight_smile:

Thanks.