使用Libgdx获取DesktopLauncher的变量

时间:2015-05-18 08:43:35

标签: java nullpointerexception get libgdx

我正在尝试创建一个2D游戏,现在我需要游戏宽度。我试图使用Gdx.graphics.getWidth(),但这给了我一个nullpointer。在浏览网页后,我发现了这一点 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);
    }
}

1 个答案:

答案 0 :(得分:2)

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

在此调用之前

new LwjglApplication(new RunningMan(), config);您的游戏窗口没有宽度或高度,这就是您获得空指针异常的原因! :

这是一个如何正确设置游戏窗口的示例:

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);
    }
}