Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs
Tags
(2 edits)

Let's see what's the topic for today is... *rummaging through notes* ah right, timers and clocks. Since I haven't made many games, my knowledge on timers was, well, lacking even when searching to find suggestions to determine how much time passes in order to say this ability can be used again after 20 seconds or 2 hours has passed in-game. But after creating some of my own timers as a pet project back in October and implementing a similar method for this game, hopefully I can explain how timers work that might help other people as well.

First off, System.currentTimeMilis() vs System.nanoTime(). I decided to go with nanoTime() as most people recommended that to measure time that has passed since the method was called inside the app/game while currentTimeMillis() takes the current time of your computer's clock and turns it into milliseconds. Next, you need to imagine a stopwatch that you can start, stop, and reset so in order to start, you call nanoTime() in the constructor and assign it to a long variable called start (can also be done in a method but be careful about calling it, especially in the update method as I've accidentally reset the start timer multiple times while unaware at first) and it'll save the start time.

Then if you want to see or check how much time is passed, you can either use a variable called end that calls nanoTime() or use System.nanoTime() itself. You would then subtract end from start and then divide that number by 1,000,000,000 to get a result.

ex:

long start = System.nanoTime(); // <-- called somewhere else
long end = System.nanoTime();

if( ( (end - start) / 1000000000 ) == 2.0) {
   System.out.println("Two seconds have passed");
   start = System.nanoTime(); // <-- this might not be necessary but I need to continuously check to see
          // if a second passes. Could be a better method
}
else {
    // do nothing or something till the two seconds pass
}

And that's my method of getting a clock running that will keep track of every class that works based on the time.