### LibGDX HelloWorld Desktop Example Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/third-party/admob-in-libgdx.md Standard setup for a libGDX application on the desktop platform. ```java public class HelloWorldDesktop { public static void main (String[] argv) { new LwjglApplication(new HelloWorld(), "Hello World", 480, 320, false); } } ``` -------------------------------- ### Basic Scene2D.UI Application Setup Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/graphics/2d/scene2d/scene2d-ui.md Sets up a stage, input processor, and a root table that fills the parent. Debug lines for the table are optional. This example uses pixel coordinates. ```java private Stage stage; private Table table; public void create () { stage = new Stage(); Gdx.input.setInputProcessor(stage); table = new Table(); table.setFillParent(true); stage.addActor(table); table.setDebug(true); // This is optional, but enables debug lines for tables. // Add widgets to the table here. } public void resize (int width, int height) { stage.getViewport().update(width, height, true); } public void render () { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); stage.act(Gdx.graphics.getDeltaTime()); stage.draw(); } public void dispose() { stage.dispose(); } ``` -------------------------------- ### LibGDX AndroidLauncher Setup Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/third-party/smaato-in-libgdx.md Basic AndroidLauncher setup to create a RelativeLayout that holds both the game view and ad views. ```java public class AndroidLauncher extends AndroidApplication { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); RelativeLayout layout = new RelativeLayout(this); layout.setLayoutParams(new RelativeLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)); layout.addView(createGameView()); createAdView(layout); setContentView(layout); } private View createGameView() { View gameView = initializeForView(new MyGame(this), new AndroidApplicationConfiguration()); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT); params.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE); params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE); gameView.setLayoutParams(params); return gameView; } } ``` -------------------------------- ### LibGDX HelloWorld Android Example Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/third-party/admob-in-libgdx.md Standard setup for a libGDX application on the Android platform. ```java public class HelloWorldAndroid extends AndroidApplication { @Override public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); initialize(new HelloWorld(), false); } } ``` -------------------------------- ### LibGDX HelloWorld iOS Example Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/third-party/admob-in-libgdx.md Standard setup for a libGDX application on the iOS platform using RoboVM. ```java public class HelloWorldIOS extends Delegate { @Override protected IOSApplication createApplication() { final IOSApplicationConfiguration config = new IOSApplicationConfiguration(); config.orientationLandscape = false; config.orientationPortrait = true; return new IOSApplication(new HelloWorld(), config); } } ``` -------------------------------- ### Run libGDX Setup Tool Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/start/project-generation.md Execute the downloaded gdx-liftoff JAR file from your command line to launch the project setup tool. Replace 'x.x.x.x' with the actual version number of the downloaded JAR. ```bash java -jar gdx-liftoff-x.x.x.x.jar ``` -------------------------------- ### Minimal Render Loop Example with ImGui Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/graphics/2d/imgui.md An example of how to structure your LibGDX screen's render method to include ImGui initialization, UI drawing, and cleanup. ```java public void render() { startImGui(); ImGui.button("I'm a Button!"); endImGui(); } ``` -------------------------------- ### Complete AdMob Integration Example Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/third-party/admob-in-libgdx.md A complete example demonstrating the initialization of a custom Android layout, LibGDX view, AdMob view, and setting the layout as the activity's content view. ```java public class HelloWorldAndroid extends AndroidApplication { @Override public void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Create the layout ``` -------------------------------- ### Start GWT Development Server Source: https://github.com/libgdx/libgdx.github.io/blob/dev/_pages/dev/-contributing/from_source.md Start a local server to access the libGDX GWT tests. GL30 emulation can be enabled via URL parameters. ```bash ./gradlew tests:gdx-tests-gwt:superDev ``` ```html http://localhost:8080/index.html?useGL30=true ``` -------------------------------- ### Basic Live Wallpaper Service Setup Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/app/starter-classes-and-configuration.md Extend AndroidLiveWallpaperService and override onCreateApplication to initialize your LibGDX game. This is the fundamental setup for a live wallpaper. ```java public class MyLiveWallpaper extends AndroidLiveWallpaperService { @Override public void onCreateApplication() { AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration(); initialize(new MyGdxGame(), cfg); } } ``` -------------------------------- ### Android Camera Surface Setup Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/graphics/integrating-libgdx-and-the-device-camera.md Handles the creation and management of the camera preview surface in an Android activity. ```java public class CameraSurface extends SurfaceView implements SurfaceHolder.Callback { private SurfaceHolder holder; private Camera camera; @SuppressWarnings("deprecation") public CameraSurface(Context context) { super(context); holder = getHolder(); holder.addCallback(this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public void surfaceCreated( SurfaceHolder holder ) { try { camera = Camera.open(); camera.setPreviewDisplay( holder ); } catch( IOException e ) { e.printStackTrace(); } } public void surfaceDestroyed( SurfaceHolder holder ) { // Once the surface gets destroyed, we stop the preview mode and release // the whole camera since we no longer need it. camera.stopPreview(); camera.release(); camera = null; } public Camera getCamera() { return camera; } } ``` -------------------------------- ### Install Android APK Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/articles/maven-integration.md Use 'mvn -Pandroid install' to deploy the generated APK to a connected Android device or emulator. ```bash mvn -Pandroid install ``` -------------------------------- ### Setup Mesh and Texture Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/graphics/opengl-utils/shaders.md Create a Mesh with specified vertex attributes and load a Texture. This prepares the geometry and image data for rendering with the shader. ```java mesh = new Mesh(true, 4, 6, VertexAttribute.Position(), VertexAttribute.ColorUnpacked(), VertexAttribute.TexCoords(0)); mesh.setVertices(new float[] { -0.5f, -0.5f, 0, 1, 1, 1, 1, 0, 1, 0.5f, -0.5f, 0, 1, 1, 1, 1, 1, 1, 0.5f, 0.5f, 0, 1, 1, 1, 1, 1, 0, -0.5f, 0.5f, 0, 1, 1, 1, 1, 0, 0 }); mesh.setIndices(new short[] {0, 1, 2, 2, 3, 0}); texture = new Texture(Gdx.files.internal("bobrgb888-32x32.png")); ``` -------------------------------- ### Install LibGDX Maven Archetype Locally Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/articles/maven-integration.md Clone the archetype repository and run 'mvn install' to make it available in your local Maven repository. ```bash git clone git://github.com/libgdx/libgdx-maven-archetype.git cd libgdx-maven-archetype mvn install ``` -------------------------------- ### Example Skin JSON for UI Elements Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/graphics/2d/scene2d/skin.md A comprehensive example of a Skin JSON file defining colors, a bitmap font, and various TextButton styles. Note that resource names are referenced by string, and some properties like colors can be defined inline. ```json { com.badlogic.gdx.graphics.Color: { white: { r: 1, g: 1, b: 1, a: 1 }, red: { r: 1, g: 0, b: 0, a: 1 }, yellow: { r: 0.5, g: 0.5, b: 0, a: 1 } }, com.badlogic.gdx.graphics.g2d.BitmapFont: { medium: { file: medium.fnt } }, com.badlogic.gdx.scenes.scene2d.ui.TextButton$TextButtonStyle: { default: { down: round-down, up: round, font: medium, fontColor: white }, toggle: { down: round-down, up: round, checked: round-down, font: medium, fontColor: white, checkedFontColor: red }, green: { down: round-down, up: round, font: medium, fontColor: { r: 0, g: 1, b: 0, a: 1 } } } } ``` -------------------------------- ### Install and Run Android Application via Gradle Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/start/import-and-running.md Use these Gradle tasks to install the debug version of your Android application and then run it. The ANDROID_HOME environment variable must be set, or a local.properties file with sdk.dir must exist. ```bash ./gradlew android:installDebug android:run ``` -------------------------------- ### Example of Formatting Localized Strings Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/internationalization-and-localization.md Demonstrates using the `format` method with different keys and arguments to retrieve localized game-related strings. ```java String game = myBundle.format("game"); String mission = myBundle.format("newMission", player.getName(), nextLevel.getName()); String coveredPath = myBundle.format("coveredPath", path.getPerc()); String highScoreTime = myBundle.format("highScoreTime", highScore.getDate()); ``` -------------------------------- ### ChoiceFormat Output Example Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/internationalization-and-localization.md Shows the expected output when formatting a string with plural forms using `ChoiceFormat` for different quantities. ```text You collected no coins along the path. You collected one coin along the path. You collected 32 coins along the path. You collected hundreds of coins along the path. ``` -------------------------------- ### play-clj Hello World Game Setup Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/jvm-langs/using-libgdx-with-clojure.md Demonstrates the basic structure of a game using the play-clj library, defining a main screen with UI elements and a game loop, and setting the screen for the game. ```clojure (ns hello-world.core (:require [play-clj.core :refer :all] [play-clj.ui :refer :all])) (defscreen main-screen :on-show (fn [screen entities] (update! screen :renderer (stage)) (label "Hello world!" (color :white))) :on-render (fn [screen entities] (clear!) (render! screen entities))) (defgame hello-world :on-create (fn [this] (set-screen! this main-screen))) ``` -------------------------------- ### Unprojecting Touch/Mouse Coordinates with Camera Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/input/mouse-touch-and-keyboard.md To get the correct world position of a touch point or mouse cursor, unproject the raw screen coordinates using a camera that operates in world space. This example shows how to set up a camera and viewport, and then use `camera.unproject()` within input handling methods to convert screen coordinates to world coordinates. ```java public class SimplerTouchTest extends ApplicationAdapter implements InputProcessor { // we will use 32px/unit in world public final static float SCALE = 32f; public final static float INV_SCALE = 1.f/SCALE; // this is our "target" resolution, note that the window can be any size, it is not bound to this one public final static float VP_WIDTH = 1280 * INV_SCALE; public final static float VP_HEIGHT = 720 * INV_SCALE; private OrthographicCamera camera; private ExtendViewport viewport; private ShapeRenderer shapes; @Override public void create () { camera = new OrthographicCamera(); // pick a viewport that suits your thing, ExtendViewport is a good start viewport = new ExtendViewport(VP_WIDTH, VP_HEIGHT, camera); // ShapeRenderer so we can see our touch point shapes = new ShapeRenderer(); Gdx.input.setInputProcessor(this); } @Override public void render () { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); shapes.setProjectionMatrix(camera.combined); shapes.begin(ShapeRenderer.ShapeType.Filled); shapes.circle(tp.x, tp.y, 0.25f, 16); shapes.end(); } Vector3 tp = new Vector3(); boolean dragging; @Override public boolean mouseMoved (int screenX, int screenY) { // we can also handle mouse movement without anything pressed // camera.unproject(tp.set(screenX, screenY, 0)); return false; } @Override public boolean touchDown (int screenX, int screenY, int pointer, int button) { // ignore if its not left mouse button or first touch pointer if (button != Input.Buttons.LEFT || pointer > 0) return false; camera.unproject(tp.set(screenX, screenY, 0)); dragging = true; return true; } @Override public boolean touchDragged (int screenX, int screenY, int pointer) { if (!dragging) return false; camera.unproject(tp.set(screenX, screenY, 0)); return true; } @Override public boolean touchUp (int screenX, int screenY, int pointer, int button) { if (button != Input.Buttons.LEFT || pointer > 0) return false; camera.unproject(tp.set(screenX, screenY, 0)); dragging = false; return true; } @Override public void resize (int width, int height) { // viewport must be updated for it to work properly viewport.update(width, height, true); } @Override public void dispose () { // disposable stuff must be disposed shapes.dispose(); } @Override public boolean keyDown (int keycode) { return false; } @Override public boolean keyUp (int keycode) { return false; } @Override public boolean keyTyped (char character) { return false; } @Override public boolean scrolled (int amount) { return false; } public static void main (String[] args) { Lwjgl3ApplicationConfiguration config = new Lwjgl3ApplicationConfiguration(); config.setWindowedMode(1280, 720); new Lwjgl3Application(new SimplerTouchTest(), config); } } ``` -------------------------------- ### Quickstart: Adding Widgets to a Table Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/graphics/2d/scene2d/table.md Demonstrates the basic usage of adding widgets to a Table and setting cell properties like width. This is useful for creating simple layouts. ```java Label nameLabel = new Label("Name:", skin); TextField nameText = new TextField("", skin); Label addressLabel = new Label("Address:", skin); TextField addressText = new TextField("", skin); Table table = new Table(); table.add(nameLabel); table.add(nameText).width(100); table.row(); table.add(addressLabel); table.add(addressText).width(100); ``` -------------------------------- ### Embed GWT Example Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/misc/wiki-style-guide.md Embed GWT examples using the `embed-gwt` include. Specify the directory of the example in the libgdx-wiki-examples repository and optionally set width and height. ```html {% raw %}{% include embed-gwt.html dir='viewport-example' width="800" height="500" %}{% endraw %} ``` -------------------------------- ### Test Web Distribution with PHP Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/deployment/deploying-your-application.md Run this command to start a local web server using PHP. Access your application via `http://localhost:8080`. ```bash php -S localhost:8000 ``` -------------------------------- ### Install Android Tests Source: https://github.com/libgdx/libgdx.github.io/blob/dev/_pages/dev/-contributing/from_source.md Use this command to install the libGDX tests on your connected Android test device. ```bash ./gradlew tests:gdx-tests-android:installDebug ``` -------------------------------- ### Desktop Starter Class (LWJGL 3) Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/app/the-application-framework.md Instantiates the LWJGL 3 backend for a desktop application. Requires Lwjgl3ApplicationConfiguration and the main game class. ```java public class DesktopLauncher { public static void main(String[] args) { Lwjgl3ApplicationConfiguration config = new Lwjgl3ApplicationConfiguration(); new Lwjgl3Application(new MyGdxGame(), config); } } ``` -------------------------------- ### LibGDX Desktop Application Setup Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/third-party/admob-in-libgdx.md This code sets up the main entry point for a LibGDX desktop application. It initializes the LwjglApplication with the game class and basic window settings. ```java package com.badlogic.gdx.helloworld; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; public class HelloWorldDesktop implements IActivityRequestHandler { private static HelloWorldDesktop application; public static void main (String[] argv) { if (application == null) { application = new HelloWorldDesktop(); } new LwjglApplication(new HelloWorld(application), "Hello World", 480, 320, false); } @Override public void showAds(boolean show) { // TODO Auto-generated method stub } } ``` -------------------------------- ### Install MinGW on Debian/Ubuntu Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/utils/jnigen.md Installs MinGW compilers for both 32-bit and 64-bit Windows development on Debian-based Linux systems. ```bash sudo apt-get install g++-mingw-w64-i686 g++-mingw-w64-x86-64 ``` -------------------------------- ### Install MinGW on Arch Linux Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/utils/jnigen.md Installs the MinGW-w64 GCC compiler on Arch Linux, which supports both 32-bit and 64-bit Windows development. ```bash sudo pacman -S mingw-w64-gcc ``` -------------------------------- ### Send HTTP GET Request Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/networking.md Construct and send an HTTP GET request using HttpRequestBuilder. A HttpResponseListener is required to handle the response. ```java HttpRequestBuilder requestBuilder = new HttpRequestBuilder(); HttpRequest httpRequest = requestBuilder.newRequest().method(HttpMethods.GET).url("https://www.google.de").build(); Gdx.net.sendHttpRequest(httpRequest, httpResponseListener); ``` -------------------------------- ### Get Display Modes for Primary Monitor (LWJGL 3) Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/graphics/querying-and-configuring-graphics.md Convenience method to get all supported display modes for the primary monitor. ```java DisplayMode[] primaryDisplayModes = Lwjgl3ApplicationConfiguration.getDisplayModes(); ``` -------------------------------- ### Install MinGW on Fedora/CentOS/RHEL Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/utils/jnigen.md Installs MinGW compilers and static winpthreads for both 32-bit and 64-bit Windows development on Fedora, CentOS, and RHEL-based systems. ```bash sudo dnf install mingw32-gcc-c++ mingw64-gcc-c++ mingw32-winpthreads-static mingw64-winpthreads-static ``` -------------------------------- ### Desktop Launcher Configuration Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/graphics/2d/orthographic-camera.md Sets up the Lwjgl3Application for the desktop, configuring window properties and launching the main application class. ```java import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application; import com.badlogic.gdx.backends.lwjgl3.Lwjgl3ApplicationConfiguration; public class DesktopLauncher { public static void main (String[] arg) { Lwjgl3ApplicationConfiguration config = new Lwjgl3ApplicationConfiguration(); config.setForegroundFPS(60); config.setTitle("orthographic-camera-example"); new Lwjgl3Application(new OrthographicCameraExample(), config); } } ``` -------------------------------- ### Basic Drawing Setup in draw() in Java Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/start/a-simple-game.md Set up the drawing environment in the `draw()` method. This includes clearing the screen, applying the viewport, setting the projection matrix for the SpriteBatch, and beginning the batch. ```java private void draw() { ScreenUtils.clear(Color.BLACK); viewport.apply(); spriteBatch.setProjectionMatrix(viewport.getCamera().combined); spriteBatch.begin(); spriteBatch.end(); } ``` -------------------------------- ### Android Starter Class Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/app/the-application-framework.md Initializes the Android backend for an Android application. Extends AndroidApplication and uses AndroidApplicationConfiguration. ```java public class AndroidStarter extends AndroidApplication { public void onCreate(Bundle bundle) { super.onCreate(bundle); AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); initialize(new MyGame(), config); } } ``` -------------------------------- ### Run Android Project with SBT Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/jvm-langs/using-libgdx-with-scala.md Start the Android project on a connected device or emulator using the 'android/start' command in SBT. This command facilitates testing your application on Android. ```bash > android/start ``` -------------------------------- ### Get Current Display Mode for Primary Monitor (LWJGL 3) Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/graphics/querying-and-configuring-graphics.md Convenience method to get the current display mode of the primary monitor. ```java DisplayMode primaryDesktopMode = Lwjgl3ApplicationConfiguration.getDisplayMode(); ``` -------------------------------- ### Fetch Native Binaries Source: https://github.com/libgdx/libgdx.github.io/blob/dev/_pages/dev/-contributing/from_source.md Fetch the pre-built native binaries from the snapshot build server. This step is recommended to verify your development environment setup before proceeding. ```bash ./gradlew fetchNatives ``` -------------------------------- ### Test Web Distribution with Python 2.x Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/deployment/deploying-your-application.md Run this command in the `html/build/dist` folder to start a simple HTTP server for testing your web application. Access it via `http://localhost:8000`. ```bash python -m SimpleHTTPServer ``` -------------------------------- ### Initialize and Use ModelCache Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/graphics/3d/modelcache.md Demonstrates the basic setup for ModelCache, including creating the cache, adding model instances, ending the cache, and rendering it with ModelBatch. Ensure to dispose of the cache when no longer needed. ```java ModelBatch batch; ModelCache cache; public void create() { //... Array instances = createTheInstanceYouWantToMerge(); cache = new ModelCache(); cache.begin(); cache.add(instances); cache.end(); //... create the batch and such } public void render() { //... call glClear and such batch.begin(); batch.render(cache, environment); batch.end(); } public void dispose() { // dispose models and such cache.dispose(); batch.dispose(); } ``` -------------------------------- ### Send HTTP GET Request with Arguments Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/networking.md Construct and send an HTTP GET request with query parameters. The parameters are appended to the URL using the 'content' method. ```java HttpRequestBuilder requestBuilder = new HttpRequestBuilder(); HttpRequest httpRequest = requestBuilder.newRequest().method(HttpMethods.GET).url("https://www.google.de").content("q=libgdx&example=example").build(); Gdx.net.sendHttpRequest(httpRequest, httpResponseListener); ``` -------------------------------- ### Get a FloatAttribute from LibGDX Material Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/graphics/3d/material-and-environment.md The `get` method retrieves an attribute by its type. It returns null if the attribute is not found. A convenience template method is also available. ```java material.get(FloatAttribute.AlphaTest); ``` ```java (FloatAttribute)material.get(FloatAttribute.AlphaTest); ``` ```java material.get(FloatAttribute.class, FloatAttribute.AlphaTest); ``` -------------------------------- ### Test Web Distribution with Python 3.x Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/deployment/deploying-your-application.md Run this command in the `html/build/dist` folder to start an HTTP server for testing your web application. Access it via `http://localhost:8000`. ```bash python -m http.server 8000 ``` -------------------------------- ### Build and Send HTTP GET Request Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/app/modules-overview.md Construct an HTTP GET request using the HttpRequestBuilder and send it via Gdx.net. Requires an HttpResponseListener to handle the response. ```java HttpRequestBuilder requestBuilder = new HttpRequestBuilder(); HttpRequest httpRequest = requestBuilder.newRequest() .method(HttpMethods.GET) .url("http://www.google.de") .build(); Gdx.net.sendHttpRequest(httpRequest, httpResponseListener); ``` -------------------------------- ### ccache Wrapper Script Example Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/utils/jnigen.md This is an example of a shell script used as a wrapper for a compiler, redirecting calls to ccache for performance benefits. Ensure the executable name matches the compiler being wrapped. ```bash echo "g++ ccache!" ccache /usr/bin/g++ "$@" ``` -------------------------------- ### Install Local JAR to Maven Repository Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/articles/dependency-management-with-gradle.md Use the Maven install plugin to add local JAR files and their sources to your local Maven repository. Replace placeholders with your file and artifact details. ```bash mvn install:install-file -Dfile= -DgroupId= -DartifactId= -Dversion= -Dpackaging= ``` ```bash mvn install:install-file -Dfile= -DgroupId= -DartifactId= -Dversion= -Dpackaging= -Dclassifier=sources ``` -------------------------------- ### Test Web Distribution with Node.js http-server Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/deployment/deploying-your-application.md Install the http-server package globally, then run this command in the `html/build/dist` folder to serve your application. Access it via `http://localhost:8080`. ```bash npm install http-server -g http-server html/build/dist ``` -------------------------------- ### Build and Send HTTP GET Request with Content Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/app/modules-overview.md Create an HTTP GET request with query parameters in the URL or content body using HttpRequestBuilder. Ensure an HttpResponseListener is provided for response handling. ```java HttpRequestBuilder requestBuilder = new HttpRequestBuilder(); HttpRequest httpRequest = requestBuilder.newRequest() .method(HttpMethods.GET) .url("http://www.google.de") .content("q=libgdx&example=example") .build(); Gdx.net.sendHttpRequest(httpRequest, httpResponseListener); ``` -------------------------------- ### Clojure Desktop Launcher Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/jvm-langs/using-libgdx-with-clojure.md Sets up the main entry point for a libGDX desktop application using Clojure, initializing the LWJGL application and enabling keyboard repeat events. ```clojure (ns demo.core.desktop-launcher (:require [demo.core :refer :all]) (:import [com.badlogic.gdx.backends.lwjgl LwjglApplication] [org.lwjgl.input Keyboard]) (:gen-class)) (defn -main [] (LwjglApplication. (demo.core.Game.) "demo" 800 600) (Keyboard/enableRepeatEvents true)) ``` -------------------------------- ### Initialize Perspective Camera Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/graphics/integrating-libgdx-and-the-device-camera.md Sets up a perspective camera with specified field of view, aspect ratio, near, and far clipping planes. Position and look-at targets are also defined. ```Java @Override public void resize(int width, int height) { camera = new PerspectiveCamera(67.0f, 2.0f * width / height, 2.0f); camera.far = 100.0f; camera.near = 0.1f; camera.position.set(2.0f,2.0f,2.0f); camera.lookAt(0.0f, 0.0f, 0.0f); } ``` -------------------------------- ### Player Movement Example with Linear Impulse Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/extensions/physics/box2d.md Example of player movement using linear impulses for left/right acceleration, ensuring the player does not exceed a maximum velocity. Requires a Dynamic Body named 'player' and a MAX_VELOCITY variable. ```java Vector2 vel = this.player.body.getLinearVelocity(); Vector2 pos = this.player.body.getPosition(); // apply left impulse, but only if max velocity is not reached yet if (Gdx.input.isKeyPressed(Keys.A) && vel.x > -MAX_VELOCITY) { this.player.body.applyLinearImpulse(-0.80f, 0, pos.x, pos.y, true); } // apply right impulse, but only if max velocity is not reached yet if (Gdx.input.isKeyPressed(Keys.D) && vel.x < MAX_VELOCITY) { this.player.body.applyLinearImpulse(0.80f, 0, pos.x, pos.y, true); } ``` -------------------------------- ### Build Runnable Desktop JAR Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/articles/maven-integration.md Execute 'mvn -Pdesktop package' to create a self-contained JAR file for the desktop application. ```bash mvn -Pdesktop package ``` -------------------------------- ### Java Runtime Environment Fatal Error Example Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/extensions/physics/bullet/bullet-wrapper-debugging.md This is an example of a fatal error log from the Java Runtime Environment that may occur when using the Bullet Wrapper. It indicates a crash in native code and provides a path to a log file for more details. ```text # A fatal error has been detected by the Java Runtime Environment: # # EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x000000006a49a450, pid=4040, tid=3912 # # JRE version: Java(TM) SE Runtime Environment (8.0_05-b13) (build 1.8.0_05-b13) # Java VM: Java HotSpot(TM) 64-Bit Server VM (25.5-b02 mixed mode windows-amd64 compressed oops) # Problematic frame: # C [gdx-bullet64.dll+0x19a450] # # Failed to write core dump. Minidumps are not enabled by default on client versions of Windows # # An error report file with more information is saved as: # C:\Xoppa\code\libgdx\tests\gdx-tests-lwjgl\hs_err_pid4040.log # # If you would like to submit a bug report, please visit: # http://bugreport.sun.com/bugreport/crash.jsp # The crash happened outside the Java Virtual Machine in native code. # See problematic frame for where to report the bug. # AL lib: (EE) alc_cleanup: 1 device not closed ``` -------------------------------- ### Create and Use PieMenu Widget Source: https://github.com/libgdx/libgdx.github.io/blob/dev/_posts/2021/2021-04-24-pie-menu.md Demonstrates how to set up a PieMenu widget, customize its style, add a listener for selection events, populate it with actors, and include it in the Stage. Requires LibGDX and Scene2D dependencies. ```java /* Setting up and creating the widget. */ PieMenu.PieMenuStyle style = new PieMenu.PieMenuStyle(); style.sliceColor = new Color(.33f,.33f,.33f,1); // "style" variables affect the way the widget looks PieMenu menu = new PieMenu(skin.getRegion("white"), style, 80); // "white" would be a 1x1 white pixel /* Adding a listener. */ menu.addListener(new ChangeListener() { @Override public void changed(ChangeEvent event, Actor actor) { System.out.println("The selected index is: " + menu.getSelectedIndex()); } }); /* Populating the widget. */ final int PIE_SLICES = 8; for (int i = 0; i < PIE_SLICES; i++) { Label label = new Label(Integer.toString(i), skin); menu.addActor(label); } /* Including the widget in the Stage. */ stage.addActor(menu); ``` -------------------------------- ### Initialize ScissorStack and Rectangles Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/graphics/2d/masking.md Set up the ShapeRenderer, camera, and calculate initial scissor rectangles. Ensure the camera is correctly oriented and the projection matrix is set. ```java /* Some attributes we're gonna need. */ private ShapeRenderer shapeRenderer; private Rectangle scissors1, scissors2; @Override public void create() { /* The ScissorStack needs a camera to transform the clipping rectangles. */ OrthographicCamera camera = new OrthographicCamera(); camera.setToOrtho(false, CAMERA_WIDTH, CAMERA_HEIGHT); /* We can use a SpriteBatch or a ShapeRenderer to draw our masked elements. */ shapeRenderer = new ShapeRenderer(); shapeRenderer.setAutoShapeType(true); shapeRenderer.setProjectionMatrix(camera.combined); /* Increase the OpenGL line thickness for better visualization. */ Gdx.gl.glLineWidth(2); /* scissors1 and scissors2 store the results of calculateScissors(...). * clipBounds is used to define the x, y, width and height of the clipping rectangles. */ scissors1 = new Rectangle(); Rectangle clipBounds = new Rectangle(100, 100, 200, 200); ScissorStack.calculateScissors(camera, shapeRenderer.getTransformMatrix(), clipBounds, scissors1); scissors2 = new Rectangle(); clipBounds.set(50f, 50f, 100f, 100f); ScissorStack.calculateScissors(camera, shapeRenderer.getTransformMatrix(), clipBounds, scissors2); } ``` -------------------------------- ### Query Primary Monitor Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/graphics/querying-and-configuring-graphics.md Get the primary monitor instance. This is useful for general display operations. ```java Monitor primary = Gdx.graphics.getPrimaryMonitor(); ``` -------------------------------- ### OrthographicCamera Example ApplicationListener Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/graphics/2d/orthographic-camera.md Implements the main application logic, handling camera creation, input processing for movement and zoom, and rendering the game world. Requires `sc_map.png` in the assets. ```java import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.OrthographicCamera; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.MathUtils; public class OrthographicCameraExample implements ApplicationListener { static final int WORLD_WIDTH = 100; static final int WORLD_HEIGHT = 100; private OrthographicCamera cam; private SpriteBatch batch; private Sprite mapSprite; private float rotationSpeed; @Override public void create() { rotationSpeed = 0.5f; mapSprite = new Sprite(new Texture(Gdx.files.internal("sc_map.png"))); mapSprite.setPosition(0, 0); mapSprite.setSize(WORLD_WIDTH, WORLD_HEIGHT); float w = Gdx.graphics.getWidth(); float h = Gdx.graphics.getHeight(); // Constructs a new OrthographicCamera, using the given viewport width and height // Height is multiplied by aspect ratio. cam = new OrthographicCamera(30, 30 * (h / w)); cam.position.set(cam.viewportWidth / 2f, cam.viewportHeight / 2f, 0); cam.update(); batch = new SpriteBatch(); } @Override public void render() { handleInput(); cam.update(); batch.setProjectionMatrix(cam.combined); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); batch.begin(); mapSprite.draw(batch); batch.end(); } private void handleInput() { if (Gdx.input.isKeyPressed(Input.Keys.A)) { cam.zoom += 0.02; } if (Gdx.input.isKeyPressed(Input.Keys.Q)) { cam.zoom -= 0.02; } if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) { cam.translate(-3, 0, 0); } if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) { cam.translate(3, 0, 0); } if (Gdx.input.isKeyPressed(Input.Keys.DOWN)) { cam.translate(0, -3, 0); } if (Gdx.input.isKeyPressed(Input.Keys.UP)) { cam.translate(0, 3, 0); } if (Gdx.input.isKeyPressed(Input.Keys.W)) { cam.rotate(-rotationSpeed, 0, 0, 1); } if (Gdx.input.isKeyPressed(Input.Keys.E)) { cam.rotate(rotationSpeed, 0, 0, 1); } cam.zoom = MathUtils.clamp(cam.zoom, 0.1f, 100/cam.viewportWidth); float effectiveViewportWidth = cam.viewportWidth * cam.zoom; float effectiveViewportHeight = cam.viewportHeight * cam.zoom; cam.position.x = MathUtils.clamp(cam.position.x, effectiveViewportWidth / 2f, 100 - effectiveViewportWidth / 2f); cam.position.y = MathUtils.clamp(cam.position.y, effectiveViewportHeight / 2f, 100 - effectiveViewportHeight / 2f); } @Override public void resize(int width, int height) { cam.viewportWidth = 30f; cam.viewportHeight = 30f * height/width; cam.update(); } @Override public void resume() { } @Override public void dispose() { mapSprite.getTexture().dispose(); batch.dispose(); } @Override public void pause() { } } ``` -------------------------------- ### Get Pointer Pressure Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/input/polling.md Obtain the pressure applied by a pointer, returning a value between 0 and 1. ```java Gdx.input.getPressure() ``` -------------------------------- ### Start Camera Preview Asynchronously Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/graphics/integrating-libgdx-and-the-device-camera.md Initiates the camera preview using `camera.startPreview()`. This operation is wrapped in a `Runnable` and posted to the activity's handler to ensure it runs on the UI thread. ```java @Override public synchronized void startPreviewAsync() { Runnable r = new Runnable() { public void run() { startPreview(); } }; activity.post(r); } @Override public synchronized void startPreview() { // ...and start previewing. From now on, the camera keeps pushing preview // images to the surface. if (cameraSurface != null && cameraSurface.getCamera() != null) { cameraSurface.getCamera().startPreview(); } } ``` -------------------------------- ### Add LibGDX Dependencies to pom.xml Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/articles/maven-integration.md Include these dependencies in your project's pom.xml for a desktop-only LibGDX setup. ```xml com.badlogicgames.gdx gdx 1.12.1 com.badlogicgames.gdx gdx-backend-lwjgl3 1.12.1 com.badlogicgames.gdx gdx-platform 1.12.1 natives-desktop ``` -------------------------------- ### Android MainActivity Setup for Camera Preview Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/graphics/integrating-libgdx-and-the-device-camera.md Configure the Android application to use a transparent GL surface and initialize the LibGDX application with a device camera controller. Ensure the GL view supports an alpha channel for camera preview visibility. ```java package com.johnny.camerademo; import android.graphics.PixelFormat; import android.os.Bundle; import android.view.SurfaceView; import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; public class MainActivity extends AndroidApplication { private int origWidth; private int origHeight; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration(); cfg.useGL20 = false; // we need to change the default pixel format - since it does not include an alpha channel // we need the alpha channel so the camera preview will be seen behind the GL scene cfg.r = 8; cfg.g = 8; cfg.b = 8; cfg.a = 8; DeviceCameraControl cameraControl = new AndroidDeviceCameraController(this); initialize(new CameraDemo(cameraControl), cfg); if (graphics.getView() instanceof SurfaceView) { SurfaceView glView = (SurfaceView) graphics.getView(); // force alpha channel - I'm not sure we need this as the GL surface is already using alpha channel glView.getHolder().setFormat(PixelFormat.TRANSLUCENT); } // we don't want the screen to turn off during the long image saving process graphics.getView().setKeepScreenOn(true); // keep the original screen size origWidth = graphics.getWidth(); origHeight = graphics.getHeight(); } public void post(Runnable r) { handler.post(r); } public void setFixedSize(int width, int height) { if (graphics.getView() instanceof SurfaceView) { SurfaceView glView = (SurfaceView) graphics.getView(); glView.getHolder().setFormat(PixelFormat.TRANSLUCENT); glView.getHolder().setFixedSize(width, height); } } public void restoreFixedSize() { if (graphics.getView() instanceof SurfaceView) { SurfaceView glView = (SurfaceView) graphics.getView(); glView.getHolder().setFormat(PixelFormat.TRANSLUCENT); glView.getHolder().setFixedSize(origWidth, origHeight); } } } ``` -------------------------------- ### Getting Tile Layer Dimensions Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/graphics/2d/tile-maps.md Query the number of columns and rows in a TiledMapTileLayer to understand its grid size. ```java int columns = tileLayer.getWidth(); int rows = tileLayer.getHeight(); ``` -------------------------------- ### Get TextButtonStyle from Skin Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/graphics/2d/scene2d/skin.md Retrieves a TextButtonStyle from the skin by its registered name. This style can then be used to construct a TextButton. ```java TextButtonStyle buttonStyle = skin.get("bigButton", TextButtonStyle.class); TextButton button = new TextButton("Click me!", buttonStyle); ``` -------------------------------- ### AndroidLauncher Activity for Fragment Integration Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/app/starter-classes-and-configuration.md This example demonstrates how to modify the AndroidLauncher Activity to host a libGDX game within a Fragment. It includes setting up the Fragment and handling the Activity lifecycle. ```java // 2. Change AndroidLauncher activity to extend FragmentActivity, not AndroidApplication // 3. Implement AndroidFragmentApplication.Callbacks on the AndroidLauncher activity public class AndroidLauncher extends FragmentActivity implements AndroidFragmentApplication.Callbacks { @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 6. Finally, replace the AndroidLauncher activity content with the libGDX Fragment. GameFragment fragment = new GameFragment(); FragmentTransaction trans = getSupportFragmentManager().beginTransaction(); trans.replace(android.R.id.content, fragment); trans.commit(); } // 4. Create a Class that extends AndroidFragmentApplication which is the Fragment implementation for libGDX. public static class GameFragment extends AndroidFragmentApplication { // 5. Add the initializeForView() code in the Fragment's onCreateView method. @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return initializeForView(new MyGdxGame()); } } @Override public void exit() {} } ``` -------------------------------- ### Java Comment Example Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/start/a-simple-game.md Illustrates how to write single-line comments in Java. These are ignored by the compiler and used for code explanation. ```java // This is a comment. It will be ignored by the compiler. ``` -------------------------------- ### Set up Kotlin Gradle Plugin Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/jvm-langs/using-libgdx-with-kotlin.md Add the Kotlin Gradle plugin to your parent project's build.gradle file. Ensure you replace '' with the desired Kotlin version. ```gradle buildscript { ext.kotlinVersion = '' dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" } } ``` -------------------------------- ### Run and Test HTML5 Project with Maven Source: https://github.com/libgdx/libgdx.github.io/blob/dev/wiki/articles/maven-integration.md Execute this command to run and test your LibGDX HTML5 project. Access the application via the specified local URL. ```bash mvn -Phtml install ```