我正在制作太空侵略者游戏。这是主要活动:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// Get a Display object to access screen details
Display display = getWindowManager().getDefaultDisplay();
// Load the resolution into a Point object
Point size = new Point();
display.getSize(size);
spaceInvadersEngine = new SpaceInvadersEngine(this, size.x, size.y);
setContentView(spaceInvadersEngine);
}
// This method executes when the player starts the game
@Override
protected void onResume() {
super.onResume();
// Tell the gameView resume method to execute
spaceInvadersEngine.resume();
}
// This method executes when the player quits the game
@Override
protected void onPause() {
super.onPause();
// Tell the gameView pause method to execute
spaceInvadersEngine.pause();
}
类SpaceInvadersEngine
有两个主要功能update()
完成所有计算的地方和draw()
我绘制所有元素的地方。添加更多元素后,游戏可以工作,但它很慢,所以我决定将其分成更多线程。 这是我的代码SpaceInvadersEngine
public void resume() {
playing = true;
gameThread = new Thread(runnable);
gameThread.start();
drawThread = new Thread(this);
drawThread.start();
}
在gameThread
可运行的我有
while(playing){update();}
对于run()
drawThread
,我只有draw();
在游戏加载和准备新关卡(创建新的入侵者和升级对象)时,最多需要 5 秒和游戏冻结。如何消除等待时间?当我也尝试用runnable
drawThread
时,它不会绘制任何东西。
另外,出于某种原因,当我使用两个线程时,我的ship
有时会在一帧中随机闪烁为大图像,然后恢复正常,它不是在单个线程中闪烁吗?
我建议您将 Kotlin 语言与异步代码的协程一起使用。开始使用它并不难,它可以真正提高整体性能和代码可读性。
fun exampleMethod() {
// Starts a new coroutine on Dispatchers.Main as it's the scope's default
val job1 = scope.launch {
// New coroutine with CoroutineName = "coroutine" (default)
}
// Starts a new coroutine on Dispatchers.Default
val job2 = scope.launch(Dispatchers.Default + "BackgroundCoroutine") {
// New coroutine with CoroutineName = "BackgroundCoroutine" (overridden)
}
}
如果您愿意稍微改变技术,请查看此内容并尝试协程。这是在Android上处理长时间运行的任务的一种新鲜而伟大的方法。此外,您还可以找到许多关于它们的文章和示例。 使用 Kotlin 协程提高应用性能