I use ktx.
我用KTX。
I have the code below:
我有以下代码:
abstract class BaseScreen(val game: PKGame) : KtxScreen {
val stage: Stage
init {
stage = PStage(ScreenViewport())
Gdx.input.inputProcessor = stage
}
override fun render(delta: Float) {
stage.act()
stage.draw()
}
override fun resize(width: Int, height: Int) {
stage.viewport.update(width, height, true)
}
override fun dispose() {
stage.dispose()
}
}
class LoadingScreen(game: PKGame): BaseScreen(game) {
val loadingState by lazy { scene2d.visLabel("Loading...") }
override fun show() {
TextureAssets.entries.forEach { game.assets.load(it) }
stage.actors {
visTable {
center()
setFillParent(true)
add(loadingState)
row()
visLabel("Click to start game")
}
}
}
override fun render(delta: Float) {
game.assets.update()
if (Gdx.input.isTouched && game.assets.isFinished) {
game.addScreen(MainMenu(game))
game.setScreen<MainMenu>()
game.removeScreen<LoadingScreen>()
dispose()
}
if (game.assets.isFinished) {
loadingState.setText("Finished")
}
debug { stage.actors.toString() }
super.render(delta)
}
}
Why it showed twice? And how can I fix this problem?
为什么它显示了两次?我该如何解决这个问题呢?
It is expected that the label "Click to start game" show just once.
预计“点击开始游戏”的标签只会显示一次。
I hove tried removing the code
我试着删除了代码
if (game.assets.isFinished) {
loadingState.setText("Finished")
}
but it still happened.
但它还是发生了。
Then, I tried removing add(loadingState)
and it rendered as expected.
然后,我尝试删除Add(LoadingState),它按预期呈现。
更多回答
What do you mean by rendered twice? You can see it in two places on the screen at once?
渲染两次是什么意思?你可以同时在屏幕上的两个地方看到它吗?
Yes. I have already uploaded the result image and the code of BaseScreen
.
是。我已经上传了结果图片和BaseScreen的代码。
I don't use Screen or the libKTX Scene2D stuff, but my best guess is that your show()
is gettting called more than once so the table is added to your scene twice. This would explain why they aren't overlapping, but just one under the other. Maybe something to do with how you're using a base class (which IMO should be avoided for something as monolithic as a whole screen because it breaks the composition before inheritance principle). I would set a breakpoint in there and use the debugger to see if it's getting called twice and if so, from where.
我不使用Screen或libKTX Scene2D内容,但我最好的猜测是您的show()被多次调用,因此该表被添加到您的场景中两次。这就解释了为什么它们不是重叠的,而是一个在另一个下面。可能与您如何使用基类有关(对于像整个屏幕这样单一的东西,应该避免使用IMO,因为它打破了组合先于继承的原则)。我会在其中设置一个断点,并使用调试器查看它是否被调用了两次,如果是,从哪里调用。
It seems that you are right.When I move the codes from show()
into init
, it shows as expected.
看起来您是对的。当我将代码从show()移到init中时,它会显示出预期的效果。
If that worked to fix it, there is probably still a lurking bug in your BaseScreen class.
如果这样做可以修复它,那么您的BaseScreen类中可能仍然潜伏着一个错误。
我是一名优秀的程序员,十分优秀!