Reputation: 769
I'm trying to update the canvas every 100ms using postDelayed() and then invalidate() (which calls onDraw again), but for some reason it will update by 30-50ms. I have debug messages printing out every time the onUpdate() function is called and the timestamps are spaced apart by 30-50ms. Why is it going so much faster than I want it to go? Usually, you'd expect functions run using a delay to be slower than what you specified.
private int FRAME_RATE = 100;
protected void onDraw(Canvas c) {
onDrawAnimation(c);
// Delay the next update by FRAME_RATE milliseconds
_h.postDelayed(_game_loop, FRAME_RATE);
}
private Runnable _game_loop = new Runnable() {
@Override
public void run() {
if (!_paused) {
onUpdate(); // Update locations/speed
invalidate(); // Update visuals (ends up calling onDraw)
}
}
};
Upvotes: 0
Views: 505
Reputation: 3958
Do it like this.
private Runnable _game_loop = new Runnable() {
@Override
public void run() {
_h.postDelayed(_game_loop, FRAME_RATE);
if (!_paused) {
onUpdate(); // Update locations/speed
invalidate(); // Update visuals (ends up calling onDraw)
}
}
};
Also, don't forget to remove all delayed callbacks:
public void onPause(){
_h.removeCallbacks(_game_loop);
// or _h.removeCallbacksAndMessages(null);
// to remove everything
}
You will probably want to separate onUpdate()
and invalidate()
in different methods and call them at different intervals.
Usually, you need to update the visuals much more often than the game logic, and you want to keep the visual refresh as lightweight as possible. In you code, if you are doing something that takes longer than 100 milliseconds, you will get visible stuttering.
Upvotes: 3