I am trying to create a 2d game and right now I need the games width. I tried to use Gdx.graphics.getWidth() but that gives me a nullpointer. After searching through the web I came upon this http://www.badlogicgames.com/forum/viewtopic.php?f=15&t=13984 That is the explanation but as you can see in my code I am using constants and scaling. It is one of my teammates that has written the code below so I don't want to change it too much. However can somebody please explain to me how I can get the width of the game from this situation? Thanks
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);
}
}
you can't get the Width()
of your game window in this stage because it's not already set .
new LwjglApplication(new RunningMan(), config);
before this call your game window doesn't have a width or height , this is why you are getting a null pointer exception ! :
here is an example on how to set your game window properly :
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);
}
}