【问题标题】:Getting the variables for DesktopLauncher using Libgdx使用 Libgdx 获取 DesktopLauncher 的变量
【发布时间】:2015-05-18 08:43:35
【问题描述】:

我正在尝试创建 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);
    }
}

【问题讨论】:

    标签: java nullpointerexception get libgdx


    【解决方案1】:

    在此阶段您无法获取游戏窗口的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);
        }
    }
    

    【讨论】:

    • 谢谢,但我不太明白我应该做什么?而不是 new LwjglApplication();我应该写新的 LwjglApplication(new RunningMan(), config); ?
    • 您需要设置窗口的宽度和高度
    • 抱歉有点慢,你能用代码告诉我吗?
    • 我已经发布了我的答案示例
    • 非常感谢!它看起来确实与我的代码非常相似。我认为唯一真正的区别是 vSynchEnabled = true;我是否正确假设我只需要在设置宽度和高度之前添加该行,就像我已经做的那样?毕竟 Runningman.SCALE、V_WIDTH 和 V.HEIGHT 都是常量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    • 2017-08-24
    相关资源
    最近更新 更多