Search code examples
javatimercountdownnanotime

How to keep track of the elapsed time in a tick method?


In a tick() method, you can't have an int startTime = System.nanoTime() because it will constantly be updating it.

I need to find the elapsed time within the tick method, so that every 2 seconds a new object gets spawned.

public void tick() {

    long startTime = System.nanoTime();

        // wave 1
        if (wave == 1) {

            float k = System.nanoTime() - startTime;
            /* won't work because "startTime" is constantly updating */

            if (k >= 2 && k <= 3) {
                handler.addObject(new BasicEnemy());
            } else if (k >= 4 && k <= 5) {
                handler.addObject(new BasicObject());
            } else if (k >= 6 && k <= 7) {
                handler.addObject(new BasicEnemy());
            }
        }

        // wave 2
        if (wave == 2) {

            float k = System.nanoTime() - startTime;
            /* won't work because "startTime" is constantly updating */

            if (k >= 2 && k <= 3) {
                handler.addObject(new BasicEnemy());
            } else if (k >= 4 && k <= 5) {
                handler.addObject(new BasicObject());
            } else if (k >= 6 && k <= 7) {
                handler.addObject(new BasicEnemy());
            }
        }
    }
}

The above is a small snippet of the code. How would I go about finding the elapsed time in the tick method and having it restart its count for every if statement?

Thanks for the help :)


Solution

  • You would need to hold the timeAtLastAccept outside the tick() method like so:

    long timeAtLastAccept = System.nanoTime();
    public void tick(){
        if(System.nanoTime()-timeAtLastAccept >threshold) {
             //Spawn your objects!
             timeAtLastAccept = System.nanoTime();
        } 
    
        //do ticky things
    }