An easy way to count up at a constant (frame-independant) rate.

Hi all,

I wanted a more convenient way to do cooldown timers in my game (and just add numbers together at a certain rate without manually using delta time and without the hassle of using really small constants with it), so I made this little snippet:


public static double getConstant(double amount_to_add, double per_x_seconds) {
    if (per_x_seconds <= 0) {
        System.out.println("Time cannot be less than or equal to 0!");
        return 0;
    }
    double time_in_mills = per_x_seconds * 1000;
    double amount_to_add_per_frame = amount_to_add / time_in_mills;
    amount_to_add_per_frame=amount_to_add_per_frame * deltaTime;
    return amount_to_add_per_frame;
}

It will return a constant that increases/decreases a variable to the number you specify in the time you specify.

e.g.


double x = 0; 
while (x < 5) {
    x+=getConstant(5, 10); //in 10 seconds, x will be 5
}

It includes delta time as well, and you can easily change it to make delta a parametre if you want. I know this is simple but it is very useful to me and I wanted to share. Have a good day :slight_smile:

edit: Added an error if the specified time span is <=0 (thanks, Riven!)

Make your code stricter. If per_x_seconds <= 0.0, you should throw an exception, as the callsite is clearly in an invalid state. Never have silent errors, this is neither PHP nor C. :point:

Noted, thanks! 8)

I think Riven meant a little stricter than a System.out.println(…) statement. Something along the lines of throwing an actual exception so the code can gracefully fail instead of continuing to run in an erred state. :wink:

Ah, I see. Although in my case, returning 0 isn’t an error. In my code I have a statistic called Obnoxiousness, which is a scale from 0-100. Sheep will bleat more if their obnoxiousness value is higher. If their obnoxious value is 0, they will not make any noise.

Fair enough; however, I think the initial point was to make it a tad more robust for others who may wish to utilize your code. Their use cases may not be the same. It’s just a suggestion though. Sharing with the community is always an appreciated gesture and people can modify as their needs dictate. :slight_smile:

Check if it’s <= 0 not just ==0.

Tsk. How sloppy of me. I’ll change it. ;D