使用 Libgdx 获取 DesktopLauncher 的变量

Getting the variables for DesktopLauncher using Libgdx

我正在尝试创建一个 2d 游戏,现在我需要游戏宽度。我尝试使用 Gdx.graphics.getWidth() 但这给了我一个空指针。通过网络搜索后,我发现了这个 http://www.badlogicgames.com/forum/viewtopic.php?f=15&t=13984 这就是解释,但正如您在我的代码中看到的那样,我使用的是常量和缩放比例。是我的一位队友编写了下面的代码,所以我不想对其进行太多更改。但是有人可以向我解释一下如何从这种情况下获得游戏的宽度吗?谢谢

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import edu.chalmers.RunningMan.RunningMan;
import static edu.chalmers.RunningMan.utils.Constants.V_HEIGHT;
import static edu.chalmers.RunningMan.utils.Constants.V_WIDTH;

public class DesktopLauncher {
    public static void main (String[] arg) {
        LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();

        config.title = RunningMan.TITLE;
        config.width = V_WIDTH * RunningMan.SCALE;
        config.height = V_HEIGHT * RunningMan.SCALE;
        new LwjglApplication(new RunningMan(), config);
    }
}

您无法在此阶段获得游戏 window 的 Width(),因为它尚未设置。

new LwjglApplication(new RunningMan(), config); 在此调用之前,您的游戏 window 没有宽度或高度,这就是您收到空指针异常的原因! :

这里有一个关于如何正确设置游戏 window 的示例:

public class DesktopLauncher {
    public static void main (String[] arg) {
        LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration();
        cfg.title = " Game Name ";
        cfg.vSyncEnabled = true;
        cfg.width = 900;  < ---- here your game window width  will be set the firs time 
        cfg.height = 600;  < --- here yout game window height will be set for the first time 

        new LwjglApplication(new MainGame(), cfg);
    }
}