我正在使用Canvas/Surfaceview
线程开发 2d 游戏并且遇到问题。所以我想要完成的是背景中的一些事情,例如:每秒SpawnEnemy()
或滴答秒或攻击。
我试过 Thread.wait 但这只会引起痛苦并使我的游戏达到 2fps。
这是我的游戏循环:
import android.graphics.Canvas;
public class GameLoopThread extends Thread {
static final long FPS = 20;
private GameView view;
private boolean running = false;
public GameLoopThread(GameView view) {
this.view = view;
}
public void setRunning(boolean run) {
running = run;
}
@Override
public void run() {
long ticksPS = 1000 / FPS;
long startTime;
long sleepTime;
while (running) {
Canvas c = null;
startTime = System.currentTimeMillis();
try {
c = view.getHolder().lockCanvas();
synchronized (view.getHolder()) {
view.onDraw(c);
}
} finally {
if (c != null) {
view.getHolder().unlockCanvasAndPost(c);
}
}
sleepTime = ticksPS - (System.currentTimeMillis() - startTime);
try {
if (sleepTime > 0)
sleep(sleepTime);
else
sleep(10);
} catch (Exception e) {}
}
}
}
所以我想要一些在后台(秒)没有线程等待的东西。