58 lines
1.6 KiB
Java
58 lines
1.6 KiB
Java
package com.flaremicro.visualforecast;
|
|
/**
|
|
* TImer class, deals with ticks, game speedup, and slowdown
|
|
* @author Vulpovile
|
|
*
|
|
*/
|
|
public class Timer {
|
|
private final int ticksPerSecond;
|
|
private long lastTickTime = 0;
|
|
private long currentTime = 0;
|
|
private long ticksPassed = 0;
|
|
/**
|
|
* Creates a timer with a set amount ticks per second
|
|
* @param ticksPerSecond
|
|
*/
|
|
public Timer(int ticksPerSecond)
|
|
{
|
|
this.ticksPerSecond = 1000/ticksPerSecond;
|
|
currentTime = System.currentTimeMillis();
|
|
lastTickTime = currentTime;
|
|
}
|
|
/**
|
|
* Resets the timer, prevents the superspeed bug when loading or generating levels
|
|
*/
|
|
public void reset()
|
|
{
|
|
currentTime = System.currentTimeMillis();
|
|
lastTickTime = currentTime;
|
|
}
|
|
/**
|
|
* Ticks the timer and returns how many ticks were missed by the game (to catch up with bad framerates)
|
|
* @return ticks passed
|
|
*/
|
|
public long tick()
|
|
{
|
|
if(ticksPassed > 0) ticksPassed--;
|
|
currentTime = System.currentTimeMillis();
|
|
if(lastTickTime < currentTime-ticksPerSecond)
|
|
{
|
|
ticksPassed = (currentTime-lastTickTime)/ticksPerSecond;
|
|
lastTickTime = currentTime - (currentTime-lastTickTime)%ticksPerSecond;
|
|
}
|
|
if(ticksPassed > 200L)
|
|
{
|
|
System.out.println("Time moving too fast! Did the system time change or is the game overloaded?");
|
|
System.out.println("Moving time forward " + ticksPassed + " ticks");
|
|
ticksPassed = 0;
|
|
}
|
|
else if(ticksPassed < 0L)
|
|
{
|
|
System.out.println("Time moved backwards! Did the system time change?");
|
|
System.out.println("Moving time backwards " + -ticksPassed + " ticks");
|
|
ticksPassed = 0;
|
|
}
|
|
return ticksPassed;
|
|
}
|
|
}
|