How to keep track of the time with Go modules?

Okay so I am developing a server for my game, and a fairly common thing is to keep track of time, for cooldowns, movement and etc. Now, this seems simple enough, you have either golangs time package or you can use ticks to calculate the time. I tried the second approach, which would work perfectly if not for the fact that float64 is not exactly 0.2 but rather something like 0.199999999999999998, which throws off the calculations. Actually, there is no easy way that I found to calculate seconds in decimals, eg. if the server ticks 5 times a second, it would be 0.2s, 0.4s, 0.6s… 1s, 1.2s… I’ve been thinking of using 200 instead of 0.2 and just go with that, but I hate scaling everything by 1000 in the game just for calculations to work. These time calculations and checks would be happening all the time so I cannot overengineer something or hack it up.

How do you guys go about it, I’ve been tackling this problem for a while and honestly would love to hear someone’s take on this? (pseudo code or code is greatly appreciated!)

@Nikola-Milovic I can make a few suggestions but also it would help to have a couple of direct examples of the reason you want to keep track of time. You mention for cooldowns? Can you describe it within the context of the game you’re working on?

@novabyte Well simply put, I need it for 2 cases at the moment, my units are traversing the grid at different speeds. One unit should pass from 1 tile to another in a second, while the other in less than a second for example. And for cooldowns, well just want to make sure if the correct amount of time passed since the last cast. I am not sure how to provide more details than this, really just elementary stuff. I have a World struct that is passed around the match state as it holds all of the information about the current game situation. The tick rate is fairly low, 5 at the moment, subject to change, but it’s not a real-time game and it’s played by the AI.

1 Like

The most straightforward approach is use ticks for everything except displaying timers to the user.

Use ticks for server match handler state, expressing durations of actions/cooldowns, calculations for progressing those durations etc. When the client must display anything time-based to the user use tick numbers and rate to convert to a human-readable time value, interpolate as necessary between the increments dictated by tick rate.

If you use ticks the authoritative server calculations will always be accurate (or as accurate as you care to make them based on tick rate, at some point there’s no way to avoid 2 things happening “at the same time”) and even if clients must use floats the user won’t perceive any difference between 0.2s and 0.19999s.

1 Like

Yeah, thank you. I am currently using that as it’s the easiest to setup. I’ll leave the discussion up for other suggestions as well, as nova said he has a few ideas.