kotlin - 我们可以使用类作为方法吗

标签 kotlin libgdx

我正在分析一个游戏项目,该项目的主类有一个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);
    }
}
因此,当从initializeLevelScreen中两次调用Parallax时,实际上是两次调用了构造函数(因此产生了2个新对象)。
在此处阅读有关Kotlin中构造函数的更多信息:https://kotlinlang.org/docs/reference/classes.html#constructors

关于kotlin - 我们可以使用类作为方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63254437/

相关文章:

java - 追加到 Kotlin 数据类 ArrayList

java - Libgdx : setting another screen, 但旧屏幕上的按钮仍处于 Activity 状态

java - 非常简单的 2D 游戏中的 libgdx 像素碰撞

java - Eclipse Oxygen 中的 GWT 编译错误

java - 使用 Apache-POI 获取 docx 的每个段落的行

java - 如何在 Recyclerview GridLayout 之间添加 Admob Ad

android - ViewModel 支持属性 [kotlin]

java - 使用 Retrofit 发送 FormUrlEncoded 时出现问题

java - 在 LibGDX 中找不到图像

java - 通过插值在重心坐标处获得适当的 UV