- Learning Libgdx Game Development
- Andreas Oehlke
- 1485字
- 2021-08-06 16:38:55
Modules
Libgdx provides six core modules that allow you to access the various parts of the system your application will run on. What makes these modules so great for you as a developer is that they provide you with a single Application Programming Interface (API) to achieve the same effect on more than just one platform. This is extremely powerful because you can now focus on your own application and you do not have to bother with the specialties that each platform inevitably brings, including the nasty little bugs that may require tricky workarounds. This is all going to be transparently handled in a straightforward API which is categorized into logic modules and is globally available anywhere in your code, since every module is accessible as a static
field in the Gdx
class.
Naturally, Libgdx does always allow you to create multiple code paths for per-platform decisions. For example, you could conditionally increase the level of detail in a game when run on the desktop platform, since desktops usually have a lot more computing power than mobile devices.
The application module
The application module can be accessed through Gdx.app
. It gives you access to the logging facility, a method to shutdown gracefully, persist data, query the Android API version, query the platform type, and query the memory usage.
Logging
Libgdx employs its own logging facility. You can choose a log level to filter what should be printed to the platform's console. The default log level is LOG_INFO
. You can use a settings file and/or change the log level dynamically at runtime using the following code line:
Gdx.app.setLogLevel(Application.LOG_DEBUG);
The available log levels are:
LOG_NONE
: This prints no logs. The logging is completely disabled.LOG_ERROR
: This prints error logs only.LOG_INFO
: This prints error and info logs.LOG_DEBUG
: This prints error, info, and debug logs.
To write an info, debug, or an error log to the console, use the following listings:
Gdx.app.log("MyDemoTag", "This is an info log."); Gdx.app.debug("MyDemoTag", "This is a debug log."); Gdx.app.error("MyDemoTag", "This is an error log.");
Shutting down gracefully
You can tell Libgdx to shutdown the running application. The framework will then stop the execution in the correct order as soon as possible and completely de-allocate any memory that is still in use, freeing both Java and the native heap. Use the following listing to initiate a graceful shutdown of your application:
Gdx.app.exit();
Note
You should always do a graceful shutdown when you want to terminate your application. Otherwise, you will risk creating memory leaks, which is a really bad thing. On mobile devices, memory leaks will probably have the biggest negative impact due to their limited resources.
Persisting data
If you want to persist your data, you should use the Preferences
class. It is merely a dictionary or a hash map data type which stores multiple key-value pairs in a file. Libgdx will create a new preferences file on the fly if it does not exist yet. You can have several preference files using unique names in order to split up data into categories. To get access to a preference file, you need to request a Preferences
instance by its filename as follows:
Preferences prefs = Gdx.app.getPreferences("settings.prefs");
To write a (new) value, you have to choose a key under which the value should be stored. If this key already exists in a preferences file, it will be overwritten. Do not forget to call flush()
afterwards to persist the data, or else all the changes will be lost.
prefs.putInteger("sound_volume", 100); // volume @ 100% prefs.flush();
Tip
Persisting data needs a lot more time than just modifying values in memory (without flushing). Therefore, it is always better to modify as many values as possible before a final flush()
method is executed.
To read back a certain value from a preferences file, you need to know the corresponding key. If this key does not exist, it will be set to the default value. You can optionally pass your own default value as the second argument (for example, in the following listing, 50
is for the default sound volume):
int soundVolume = prefs.getInteger("sound_volume", 50);
Querying the Android API Level
On Android, you can query the Android API Level, which allows you to handle things differently for certain versions of the Android OS. Use the following listing to find out the version:
Gdx.app.getVersion();
Note
On platforms other than Android, the version returned is always 0
.
Querying the platform type
You may want to write a platform-specific code where it is necessary to know the current platform type. The following example shows how it can be done:
switch (Gdx.app.getType()) { case Desktop: // Code for Desktop application break; case Android: // Code for Android application break; case WebGL: // Code for WebGL application break; default: // Unhandled (new?) platform application break; }
Querying memory usage
You can query the system to find out its current memory footprint of your application. This may help you find excessive memory allocations that could lead to application crashes. The following functions return the amount of memory (in bytes) that is in use by the corresponding heap:
long memUsageJavaHeap = Gdx.app.getJavaHeap(); long memUsageNativeHeap = Gdx.app.getNativeHeap();
Graphics module
The graphics module can be accessed either through Gdx.getGraphics()
or by using the shortcut variable Gdx.graphics
.
Querying delta time
Query Libgdx for the time span between the current and the last frame in seconds by calling Gdx.graphics.getDeltaTime()
.
Querying display size
Query the device's display size returned in pixels by calling Gdx.graphics.getWidth()
and Gdx.graphics.getHeight()
.
Querying the FPS (frames per second) counter
Query a built-in frame counter provided by Libgdx to find the average number of frames per second by calling Gdx.graphics.getFramesPerSecond()
.
Audio module
The audio module can be accessed either through Gdx.getAudio()
or by using the shortcut variable Gdx.audio
.
Sound playback
To load sounds for playback, call Gdx.audio.newSound()
.
The supported file formats are WAV, MP3, and OGG.
There is an upper limit of 1 MB for decoded audio data. Consider the sounds to be short effects like bullets or explosions so that the size limitation is not really an issue.
Music streaming
To stream music for playback, call Gdx.audio.newMusic()
.
The supported file formats are WAV, MP3, and OGG.
Input module
The input module can be accessed either through Gdx.getInput()
or by using the shortcut variable Gdx.input
.
In order to receive and handle input properly, you should always implement the InputProcessor
interface and set it as the global handler for input in Libgdx by calling Gdx.input.setInputProcessor()
.
Reading the keyboard/touch/mouse input
Query the system for the last x or y coordinate in the screen coordinates where the screen origin is at the top-left corner by calling either Gdx.input.getX()
or Gdx.input.getY()
.
- To find out if the screen is touched either by a finger or by mouse, call
Gdx.input.isTouched()
- To find out if the mouse button is pressed, call
Gdx.input.isButtonPressed()
- To find out if the keyboard is pressed, call
Gdx.input.isKeyPressed()
Reading the accelerometer
Query the accelerometer for its value on the x axis by calling Gdx.input.getAccelerometerX()
. Replace the X
in the method's name with Y
or Z
to query the other two axes. Be aware that there will be no accelerometer present on a desktop, so Libgdx always returns 0
.
Starting and canceling vibrator
On Android, you can let the device vibrate by calling Gdx.input.vibrate()
.
A running vibration can be cancelled by calling Gdx.input.cancelVibrate()
.
Catching Android soft keys
You might want to catch Android's soft keys to add an extra handling code for them. If you want to catch the back button, call Gdx.input.setCatchBackKey(true)
. If you want to catch the menu button, call Gdx.input.setCatchMenuKey(true)
.
On a desktop where you have a mouse pointer, you can tell Libgdx to catch it so that you get a permanent mouse input without having the mouse ever leave the application window. To catch the mouse cursor, call Gdx.input.setCursorCatched(true)
.
The files module
The files module can be accessed either through Gdx.getFiles()
or by using the shortcut variable Gdx.files
.
Getting an internal file handle
You can get a file handle for an internal file by calling Gdx.files.internal()
.
An internal file is relative to the assets
folder on the Android and WebGL platforms. On a desktop, it is relative to the root
folder of the application.
Getting an external file handle
You can get a file handle for an external file by calling Gdx.files.external()
.
An external file is relative to the SD card on the Android platform. On a desktop, it is relative to the user's home folder. Note that this is not available for WebGL applications.
The network module
The network module can be accessed either through Gdx.getNet()
or by using the shortcut variable Gdx.net
.
HTTP GET and HTTP POST
You can make HTTP GET and POST requests by calling either Gdx.net.httpGet()
or Gdx.net.httpPost()
.
Client/server sockets
You can create client/server sockets by calling either Gdx.net.newClientSocket()
or Gdx.net.newServerSocket()
.
Opening a URI in a web browser
To open a Uniform Resource Identifier (URI) in the default web browser, call Gdx.net.openURI(URI)
.