[libGDX] Calculate seconds based on number of ticks

I am coding a better time feature for my game and it mostly works, except when I try to calculate minutes.

Here is my code. There are 1440 ticks (ticks happen every second), 24 hours, and 60 minutes in every day.

public static void time() {
		tick++;
		minute=(tick/hour)-60;
		if(hour==13){
			toggle_time();
		}
		if(hour>24){
			hour=1;
			tick=0;
		}
		
		
		if (tick % 60 == 0) {
			hour = Math.round(tick / 60);
			
		}
		if(hour==0){
			hour=1;
		}
		if(hour==10){
			sun_set=true;
			sun_rise=false;
		}
		if(hour==20){
			sun_rise=true;
			sun_set=false;
		}
		
		rot=-(float) (hour/2*30);
		System.out.println("Time: H: "+hour+"; M: "+ minute+"; Tick: "+ tick);

	}

which outputs something like:


Time: H: 15.0; M: 3.9333344; Tick: 959.0
Time: H: 16.0; M: 4.0; Tick: 960.0
Time: H: 16.0; M: 0.0625; Tick: 961.0
Time: H: 16.0; M: 0.125; Tick: 962.0
Time: H: 16.0; M: 0.1875; Tick: 963.0
Time: H: 16.0; M: 0.25; Tick: 964.0

I’m trying to calculate current minutes in the hour based off of the ticks.

any help would be greatly appreciated! :point:

Please provide the definitions of all of the variables (Types mainly) because it seems like this might be some sort of arithmetic issue involving types.

The issue is a simple arithmetic one: minute = (tick / hour) - 60 will always return something weird. Since hour is a variable that changes based on the number of times tick % 60 == 0 is true (So at hour 1, it will be tick - 60; hour 2, it will be tick / 2 - 60). You probably want something more like: minute = tick % ticksInMinute, hour = tick % ticksInHour.

A somewhat better/easier way to keep track of this is through an accumulator type system instead. Basically, instead of what you have right now you’d do something like:


private int currentTicks;
private int hour;
private int minute;
private int minuteAccum;
private int ticksPerMinute;

public void tick() {
	currentTick++;
	minuteAccum++;
	while(minuteAccum > ticksPerMinute) {
		minuteAccum -= ticksPerMinute;
		minute++;
		while(minute > 60) {
			hour++;
			minute -= 60;
		}
	}
	
	/*
	* Do stuff based on time here.
	*/
}