我正在尝试创建一个 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);
}
}
最佳答案
在此阶段您无法获取游戏窗口的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);
}
}
关于java - 使用 Libgdx 获取 DesktopLauncher 的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30298624/