开发者

Limiting frame rate with Thread.sleep()

开发者 https://www.devze.com 2023-03-26 01:33 出处:网络
I am working on a live wallpaper, so no worries about physics collisions. I just want to have as smooth a frame rate as possible, up to a limit of 30fps to conserve battery.

I am working on a live wallpaper, so no worries about physics collisions. I just want to have as smooth a frame rate as possible, up to a limit of 30fps to conserve battery.

To do this, at the end of the loop, and I measure time since the beginning of that loop. If the frame took less than 33ms, I use Thread.sleep() to sleep the number of ms to get up to 33.

However, I know that Thread.sleep() is not super accurate, and is likely to sleep longer than I ask for. I don开发者_如何学Go't know by how much.

Is there a different method I can use that will provide a more even rate?


Yes, Thread.sleep() is not super-accurate.

You can try to use adaptive strategy -- do not just sleep(remaining), but have a variable long lastDelay, and, each time you observe too high frame rate you increase it, and Thread.sleep(lastDelay), each time you observe too low frame rate -- you decrease it. So after second or about your code find right number...

By the way, the Thread.sleep is not the best way to limit frame rate. Using of Timer is more promising -- but you'll have same problem, since Timer accuracy is likely the same, as Thread.sleep()


I'm not 100% sure about this, but have you tried using a Timer (http://developer.android.com/reference/java/util/Timer.html) and TimerTask (http://developer.android.com/reference/java/util/TimerTask.html)? You should be able to use that to schedule your updates.


30fps does not look smooth at all in a canvas animation. One should always try to keep about 60fps and then adjust the speed of sprite movement according to the screen density. Thread.sleep() is accurate enough for wallpaper or 2d game animations, one cannot notice the difference if the fps goes up or down just few frames.

Or use the so-called frame-rate-independed-movement where

deltaTime = timeNow - prevFrameTime; //for 60fps this should be ~0.016s    
object.x += speedX * deltaTime;
0

精彩评论

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