我强烈建议您有一个渲染线程(使用Canvas
/ OpenGL ES
,Canvas
可能会更容易设置)和一个放置游戏逻辑的游戏线程。
要实际“加载”游戏,您可以创建GameEngine类,并将其作为应用程序的中心点。准备好渲染器后,您可以创建GameEngine实例的回调,该实例将创建并启动两个线程,其中一个Runnable
用于渲染,另一个Runnable
用于游戏逻辑。
样例代码:
申请开始
private GameEngine engine;
private CanvasRenderer renderer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create instances of your two Runnable classes and pass that into
// the GameEngine constructor.
// Create an instance of the game engine.
engine = new GameEngine(canvasRunnable, gamelogicRunnable);
renderer = new CanvasRenderer(this, engine);
setContentView(renderer);
}
画布渲染器
private GameEngine engine;
// Save your instance from the GameEngine reference in your constrcutor and make
// a global initializion for your GameEngine instance.
@Override
public void surfaceCreated(SurfaceHolder holder) {
// One time setup here.
// When your view is ready, make this callback to the
// GameEngine.
engine.surfaceIsReady();
}
游戏引擎
private Thread canvasThread;
private CanvasRunnable canvasRunnable;
// You should be able to figure out how to create a second thread
// where you should put your game logic. :)
// Constructor stuff like creating instances of your threads
// and passing references as you wish to those.
// Don't start the threads here.
// Remember to set references from your Runnable's into your Thread's
// instances here!
/**
* Callback. Now your renderer is ready and you
* can start your threads.
*/
public void surfaceIsReady() {
thread.setName("Canvas");
thread.start();
// Same for game logic.
}