我正在分析一个游戏项目,该项目的主类有一个initialize方法。
该项目使用带有类似构造方法的类。
该方法名称是什么?其逻辑是什么?
例如
这是主类
class LevelScreen : BaseScreen(){
override fun initialize() {
Parallax(0f, 0f, mainStage, "assets/mountains0.png", 35f)
Parallax(800f, 0f, mainStage, "assets/mountains1.png", 45f)}
}
这称为类视差class Parallax(x: Float, y: Float, s: Stage, texture: String, speed: Float): BaseActor(x, y, s) {
init {
loadTexture(texture)
setSpeed(speed)
setMotionAngle(180f)
}
override fun act(dt: Float) {
super.act(dt)
applyPhysics(dt)
// if moved completely past left edge of the screen
// shift right, past other instance
if (x + width < 0)
moveBy(2 * width, 0f)
}
}
最佳答案
我还不能发表评论,所以考虑在@Bruno的答案上进行扩展。
听起来您对Parallax
类感到困惑。在Kotlin中,主要的构造函数是类头文件的一部分。因此Kotlin中的class Parallax(x: Float, y: Float, s: Stage, texture: String, speed: Float): BaseActor(x, y, s)
等同于Java中的以下代码:
class Parallax extends BaseActor {
Parallax(float x, float y, Stage s, String texture, float speed){
super(x, y, s);
}
}
因此,当从initialize
的LevelScreen
中两次调用Parallax时,实际上是两次调用了构造函数(因此产生了2个新对象)。在此处阅读有关Kotlin中构造函数的更多信息:https://kotlinlang.org/docs/reference/classes.html#constructors
关于kotlin - 我们可以使用类作为方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63254437/