开发者

Slow down a clock based on System.nanoTime();

开发者 https://www.devze.com 2023-03-23 17:25 出处:网络
I have a timer based on System.nanoTime() and I want to slow it down. I have this: elapsed =开发者_StackOverflow System.nanoTime();

I have a timer based on System.nanoTime() and I want to slow it down.

I have this:

elapsed =开发者_StackOverflow System.nanoTime();
seconds = ((elapsed -  now) / 1.0E9F);

where now is System.nanoTime(); called earlier in the class.

In order to slow it down I tried:

if(slow){
    elapsed = System.nanoTime();
    seconds = ((elapsed -  now) / 1.0E9F) * 0.5F;
}else{//The first code block

But then I run into the problem of seconds being cut in half, which is not desirable. Before slow is true, it's displaying 10 seconds to the screen, and when slow is true, it displays 5 seconds, which is not desirable.

I want to slow the timer, not cut it in half as well as slow it down

On the other hand, it slows down the time, which is what I want.

How would I slow down the time, without cutting my existing time in half?


Add to seconds rather than recalculating it from scratch each time through the loop:

elapsed = System.nanoTime();
if (slow) {
    seconds += ((elapsed -  now) / 1.0E9F) * .5F;
}
else {
    seconds += ((elapsed -  now) / 1.0E9F);
}
now = elapsed;  // so next time you just get the incremental difference


You can have a member variable that contains the multiply needed to be done. Always calculate the correct number of seconds, and when you use the timer, multiply it:

float multiple = 1.f;
//...
seconds = (elapsed -  now) / 1.0E9F;
//...
// setting timer:
somefunc(seconds * multiple);

public void setSlow(boolean slow) {
    if(slow)
        multiple = 1.0f;
    else
        multiple = 0.5f
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号