Android 游戏循环睡眠
我正在开发一款 Android 迷你游戏。我正在使用此代码进行游戏循环。
private RefreshHandler mRedrawHandler = new RefreshHandler();
class RefreshHandler extends Handler {
@Override
public void handleMessage(Message msg) {
Panel.this.update();
Panel.this.invalidate();
}
public void sleep(long delayMillis) {
this.removeMessages(101);
sendMessageDelayed(obtainMessage(101), delayMillis);
}
};
public void update() {
if (mMode == RUNNING) {
ball.update(NR_PIX);
for (int i=0; i<N; i++) {
bords[i].update(NR_PIX);
}
Panel.lastBordHeight -= NR_PIX;
if (mYBrickOffset == 0)
mYBrickOffset = mYBrick;
mYBrickOffset -= NR_PIX;
mRedrawHandler.sleep(mMoveDelay);
}
}
RefreshHandler 类来自 SnakeView 类示例。
代码工作正常。我有一个“新游戏活动”按钮。当我第一次进入活动时,它就起作用了。但如果我退出游戏并再次进入,速度会更快,这是我不明白或不明白的事情。如果我退出游戏并使用“新游戏”按钮再次进入,速度会更快。
谁能帮我解决这个问题吗?
I am working on a mini game for Android. I am using this code for the game loop.
private RefreshHandler mRedrawHandler = new RefreshHandler();
class RefreshHandler extends Handler {
@Override
public void handleMessage(Message msg) {
Panel.this.update();
Panel.this.invalidate();
}
public void sleep(long delayMillis) {
this.removeMessages(101);
sendMessageDelayed(obtainMessage(101), delayMillis);
}
};
public void update() {
if (mMode == RUNNING) {
ball.update(NR_PIX);
for (int i=0; i<N; i++) {
bords[i].update(NR_PIX);
}
Panel.lastBordHeight -= NR_PIX;
if (mYBrickOffset == 0)
mYBrickOffset = mYBrick;
mYBrickOffset -= NR_PIX;
mRedrawHandler.sleep(mMoveDelay);
}
}
The RefreshHandler class is from the SnakeView class example.
The code works ok. I have a Activity for a New Game button. When I first enter the Activity it's works. But if I exit the game and enter again the speed it's faster, thing that I don't wont or understand. If I exit the game and enter again using the New Game button the speed is faster even more.
Can anyone help me with this ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我已经成功解决了 Activity 中覆盖 onPause 的问题。这是新代码:
I have managed to solve the problem overriding onPause in Activity. Here is the new code:
调用 update() 的速度永远不会相同。一个循环可能需要 16 毫秒,下一个循环可能只需要 14 毫秒,并且会随着时间的推移而不断变化。
您需要尝试让它以固定的速率循环,这将使您的游戏以一致的速度运行。
尝试阅读以下内容: http://obviam.net/index.php/the- android-game-loop/ 这里有一个有趣的讨论:http://www.java-gaming.org/index.php?topic=21372.0
The speed of update() being called is never the same. One loop may take 16 milliseconds and the next loop may only take 14 milliseconds and it will continue to vary over time.
You need to try get it to loop at a fixed rate, this will keep your game running ant a consistent speed.
Try reading this: http://obviam.net/index.php/the-android-game-loop/ and there is an interesting discussion here: http://www.java-gaming.org/index.php?topic=21372.0