Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a Java 2D game built with libGDX, the usual Box2D route is the gdx-box2d extension: a Java API backed by native Box2D. This guide uses that wrapper—not the upstream Box2D C API and not JBox2D—and walks through setup, bodies and fixtures, fixed-step simulation, rendering, movement, contacts, sensors, and debugging.

What Box2D does—and which Java implementation to use

Box2D is a 2D rigid-body simulation library. It calculates motion, collision detection and physical responses; it does not draw sprites, load textures, or decide what a collision means to your game. In a libGDX project, the gdx-box2d extension provides the familiar World, Body, fixture, contact and joint APIs over native Box2D. See the libGDX Box2D documentation and the upstream Box2D overview.

Box2D is a good fit for platformers, top-down games, puzzles, physics toys, interactive environments and vehicle-like mechanics. It is not a 3D engine, a pixel-perfect collision system or a deformable-body simulator. A controllable character also usually needs gameplay-specific movement logic rather than being left to behave like an ordinary crate.

The libGDX extension is not automatically present in every new project: add its dependency and the appropriate platform natives. The upstream Box2D API has evolved, so its newer C examples are not drop-in Java code for libGDX. The libGDX Box2D-v3 integration request is tracked at issue 7812.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

When JBox2D makes more sense

JBox2D is a separate native-Java port of Box2D and LiquidFun. Consider it when avoiding JNI binaries is important or when the project does not depend on libGDX’s Box2D API. It is not the same library as gdx-box2d; do not mix imports such as org.jbox2d.* with com.badlogic.gdx.physics.box2d.*. Its Maven artifact is listed at Sonatype Central.

Add the libGDX Box2D dependencies

Start with a libGDX Gradle project. The official setup guide covers project creation, and the dependency-management guide documents platform-specific artifacts. The following is representative for a desktop LWJGL3 project; use the version and configurations from your generated project, and include the correct native artifacts for every target.

def gdxVersion = "1.14.2"

dependencies {
    api "com.badlogicgames.gdx:gdx:$gdxVersion"
    api "com.badlogicgames.gdx:gdx-box2d:$gdxVersion"

    implementation "com.badlogicgames.gdx:gdx-backend-lwjgl3:$gdxVersion"
    implementation "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
    implementation "com.badlogicgames.gdx:gdx-box2d-platform:$gdxVersion:natives-desktop"
}

The libGDX release listing identified 1.14.2, released May 18, 2026, as the latest release when checked on August 18, 2026; releases can change, so confirm the current release listing and keep every libGDX artifact on the same version. Android requires native artifacts for the architectures the app supports; iOS and HTML5 have their own backend-specific setup and limitations. Follow the platform forms in the dependency guide rather than assuming desktop natives cover other targets.

  • Put gdx-box2d in the module that compiles the physics code.
  • Add the matching gdx-box2d-platform artifact for each native target.
  • If startup fails with UnsatisfiedLinkError, check the native classifier, target architecture and version alignment before investigating gameplay code.

Initialize Box2D and create a world

Initialize the extension before using its physics classes, then create a World. Its constructor takes gravity and whether inactive bodies may sleep:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Box2D.init();
World world = new World(new Vector2(0f, -9.81f), true);

Gravity is expressed in world units per second squared. The libGDX guide commonly uses a downward value near -10 and recommends a consistent meter-like scale. Sleeping lets inactive bodies stop consuming simulation work until something wakes them. The Box2D.init() API documentation describes native loading; that Javadoc is for an older release, so use it for the initialization contract, not as a version guide.

A world owns its bodies, fixtures, joints and simulation state. Keep a reference to it for updates and dispose it when the game screen or owner is finished with it.

Understand worlds, bodies, shapes and fixtures

The core distinction is that a Body represents a physical object’s transform and mass properties, while its one or more Fixture objects provide collision shapes and material/filter settings. A body definition configures creation; it is not the body itself.

World and body types

  • World owns and advances the simulation.
  • BodyDef specifies initial body properties such as type, position and fixed rotation.
  • StaticBody describes fixed geometry such as a floor.
  • DynamicBody responds to gravity, forces, impulses and collisions.
  • KinematicBody is controlled by velocity or game logic rather than ordinary force-driven motion; it suits some moving platforms and scripted objects.

Shapes and fixtures

Common shapes include PolygonShape, CircleShape, EdgeShape and ChainShape. A FixtureDef associates a shape with properties such as density, friction, restitution, sensor status and collision filtering. Density contributes to a dynamic body’s mass; friction affects resistance along a surface; restitution influences bounce but does not promise a particular bounce height. A chain is an outline, not a filled solid. Decompose concave artwork into convex fixtures instead of trying to use it as one concave polygon.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Multiple fixtures on one body are useful for a player’s main collision shape plus foot sensor, a compound enemy, or a rigid object with different material regions. Use body or fixture user data to associate physics objects with game entities, for example body.setUserData(actor); see the libGDX guide.

Keep physics in world units, not pixels

Box2D behaves best with coherent, meter-like dimensions rather than screen pixels. One hundred pixels per meter is a common project convention, not an engine requirement. The libGDX Box2D guide explains the scale recommendation.

public static final float PPM = 100f; // project convention: pixels per meter

float physicsX = screenX / PPM;
float physicsY = screenY / PPM;
float screenX = physicsX * PPM;
float screenY = physicsY * PPM;

Convert dimensions and positions at the boundary between rendering and physics. Keep camera and sprite scale consistent with that convention, and do not round physics positions to integer pixels. Very large coordinates, extreme velocities and tiny shapes can all make simulation less stable.

Render from the body’s transform

For a centered sprite, copy the body’s position and angle to the sprite after stepping the world:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Vector2 position = body.getPosition();
sprite.setPosition(
    position.x * PPM - sprite.getWidth() / 2f,
    position.y * PPM - sprite.getHeight() / 2f
);
sprite.setRotation(body.getAngle() * MathUtils.radiansToDegrees);

The body is authoritative for a dynamic object. Moving only its sprite makes the visible object diverge from its collision shape. If the sprite origin is not centered, calculate its placement for that origin rather than reusing the centered formula.

Build a ground platform and falling crate

This small setup creates a static floor and a dynamic crate. PolygonShape.setAsBox takes half-width and half-height: the ground below is 10 units wide and 0.5 high, centered on its body origin.

private Body createGround(World world) {
    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.StaticBody;
    bodyDef.position.set(5f, 1f);
    Body body = world.createBody(bodyDef);

    PolygonShape shape = new PolygonShape();
    shape.setAsBox(5f, 0.25f);
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = shape;
    fixtureDef.friction = 0.8f;
    body.createFixture(fixtureDef);
    shape.dispose();
    return body;
}

private Body createCrate(World world) {
    BodyDef bodyDef = new BodyDef();
    bodyDef.type = BodyDef.BodyType.DynamicBody;
    bodyDef.position.set(5f, 5f);
    Body body = world.createBody(bodyDef);

    PolygonShape shape = new PolygonShape();
    shape.setAsBox(0.5f, 0.5f);
    FixtureDef fixtureDef = new FixtureDef();
    fixtureDef.shape = shape;
    fixtureDef.density = 1f;
    fixtureDef.friction = 0.5f;
    fixtureDef.restitution = 0.1f;
    body.createFixture(fixtureDef);
    shape.dispose();
    return body;
}

If the body origin should mark the floor’s top surface, offset the shape center below it instead: shape.setAsBox(5f, 0.25f, new Vector2(0f, -0.25f), 0f). Create and dispose temporary shapes around fixture creation, as shown; do not dispose a shape before it has been used to create the fixture.

Advance the simulation with a fixed timestep

World.step(timeStep, velocityIterations, positionIterations) advances collision detection, integration and constraint solving. The libGDX World API source documents the arguments and advises a consistent timestep. A fixed-step accumulator avoids making the simulation step depend directly on render-frame length:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
private static final float TIME_STEP = 1f / 60f;
private static final int VELOCITY_ITERATIONS = 6;
private static final int POSITION_ITERATIONS = 2;
private float accumulator;

void update(float delta) {
    delta = Math.min(delta, 0.25f);
    accumulator += delta;
    while (accumulator >= TIME_STEP) {
        world.step(TIME_STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
        accumulator -= TIME_STEP;
    }
}

The delta clamp limits the catch-up work after a pause or debugger stop. Six velocity iterations and two position iterations are starting values for a small example, not universal optimum settings; raising them can improve constraint quality at additional CPU cost. A variable step such as world.step(delta, 6, 2) is simpler for a prototype, but frame spikes and differing frame rates can produce less consistent behavior.

In a game with input, sample or apply movement on simulation ticks as appropriate to your controller, and process queued world changes after each step. Interpolation between previous and current transforms can smooth rendering when render and physics rates differ, but it is optional for a first working simulation.

Choose forces, impulses or velocity for movement

These controls serve different purposes; realistic motion and responsive controls are not always the same design goal.

Use force for sustained acceleration

body.applyForceToCenter(new Vector2(10f, 0f), true);

Forces suit continuous effects such as engines, wind and thrusters. Their effect depends on mass and how long they are applied.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use impulse for an immediate change

body.applyLinearImpulse(
    new Vector2(0f, 5f), body.getWorldCenter(), true
);

An impulse is useful for a jump, explosion or one-time knockback. For a platformer, apply a jump impulse only when the character is grounded.

Use velocity selectively for responsive control

Vector2 velocity = body.getLinearVelocity();
body.setLinearVelocity(targetSpeed, velocity.y);

Directly setting horizontal velocity is common in a platformer because it gives predictable control, but it can override physical motion if applied indiscriminately. Many games combine velocity control, impulses, damping and collision handling. A player may use fixedRotation = true to stay upright; that is a gameplay trade-off, not a default for crates, wheels or debris.

Detect overlaps, contacts and gameplay events

Register a ContactListener to receive begin, end, pre-solve and post-solve callbacks. These report physics contacts, not automatically meaningful game events:

world.setContactListener(new ContactListener() {
    @Override
    public void beginContact(Contact contact) {
        Fixture a = contact.getFixtureA();
        Fixture b = contact.getFixtureB();
        Object userA = a.getUserData();
        Object userB = b.getUserData();
        // Identify the pair and enqueue a gameplay event.
    }

    @Override public void endContact(Contact contact) { }
    @Override public void preSolve(Contact contact, Manifold oldManifold) { }
    @Override public void postSolve(Contact contact, ContactImpulse impulse) { }
});

The libGDX World API source lists these callbacks and documents restrictions on mutating a locked world. Avoid creating or destroying bodies, fixtures or joints inside a callback during a step. Record a command or gameplay event and perform the change after world.step returns:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Queue<Body> bodiesToDestroy = new ArrayDeque<>();

// From contact handling:
bodiesToDestroy.add(body);

// After world.step(...):
while (!bodiesToDestroy.isEmpty()) {
    world.destroyBody(bodiesToDestroy.remove());
}

Do not depend on fixture order in a contact, assume one logical entity has only one fixture, or retain callback objects without checking their API lifetime. Identify both participants through their fixtures, bodies, user data or an entity registry, then translate contacts into explicit events such as “player collected pickup.”

Use sensors for detection without a physical response

A sensor fixture reports overlap without pushing bodies apart. It is useful for a foot region, pickup range, trigger area or damage zone:

FixtureDef sensorDef = new FixtureDef();
sensorDef.shape = footShape;
sensorDef.isSensor = true;
player.createFixture(sensorDef);

Give sensors appropriate collision filters, often different from the main player fixture. For a grounded check, track active foot contacts rather than setting a single boolean false on every end-contact callback: the player may touch more than one surface at once. A contact count or set of active fixture pairs avoids losing grounded state when one of several contacts ends.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Filter which fixtures can collide

Collision filtering uses category bits (what a fixture is), mask bits (which categories it can interact with) and, in some cases, a group index override. A mask that excludes a category can make a valid-looking pair appear to ignore collisions.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
private static final short CATEGORY_WORLD  = 1;
private static final short CATEGORY_PLAYER = 1 << 1;
private static final short CATEGORY_ENEMY  = 1 << 2;
private static final short CATEGORY_PICKUP = 1 << 3;

FixtureDef playerFixture = new FixtureDef();
playerFixture.shape = playerShape;
playerFixture.filter.categoryBits = CATEGORY_PLAYER;
playerFixture.filter.maskBits =
        CATEGORY_WORLD | CATEGORY_ENEMY | CATEGORY_PICKUP;

Define compatible masks on the other fixtures too. For example, a pickup intended to overlap the player needs a category and mask combination that permits that pair; use a sensor when it should not cause a physical response.

Connect physics to sprites and inspect the result

Box2D does not render the game world. Keep the flow explicit: body transform to game-entity transform to sprite rendering. Before tuning artwork or movement, draw the physics geometry with Box2DDebugRenderer:

private Box2DDebugRenderer debugRenderer = new Box2DDebugRenderer();

// In render, after stepping the world:
debugRenderer.render(world, camera.combined);

The libGDX Box2D guide describes the debug renderer. It helps reveal body-position mistakes, wrong scale, missing fixtures, unexpected rotations, sprite alignment errors and collision shapes that do not match the art. Keep it enabled behind a development flag once the game has its normal renderer.

For rendering to line up, the camera matrix and physics-to-screen scale must agree. If the sprite and debug shape differ, first verify units, body origin, sprite origin and whether body angle is applied; do not compensate by moving a dynamic sprite independently.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Add joints and moving geometry when needed

Joints constrain the relationship between bodies; they are preferable to manually synchronizing separate objects when the connection itself is part of the simulation. Box2D provides joint families such as revolute (rotation around an anchor), distance, prismatic (sliding along an axis) and weld (rigid connection). A vehicle can use a body plus connected wheel bodies, while a hinged door can use a revolute joint. Create joints as part of world setup or queue their creation for after a step, and tune limits and collision behavior for the specific design.

Moving platforms or scripted doors may be kinematic bodies, while objects expected to respond to forces generally belong on dynamic bodies. Choosing the wrong type changes how collision response and motion behave; do not assume every object a player can control should be dynamic or kinematic without considering the intended interaction.

Debug common Box2D failures

Native library fails to load

An UnsatisfiedLinkError commonly means the Box2D native artifact is missing, has the wrong classifier or architecture, or does not match the Java artifact version. Check that all libGDX dependencies align, include target-specific gdx-box2d-platform artifacts, then clean and rebuild. Test the desktop backend separately before debugging mobile packaging. The dependency guide lists platform forms.

Objects move very slowly or sprites do not line up

If pixels were used as physics units, convert positions and dimensions into the chosen world scale. For sprite mismatch, check the body-to-pixel conversion, center-versus-corner origin, camera scale and body rotation. Overlay the debug renderer to isolate physics geometry from art.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Player falls through the floor

  • Confirm both bodies have fixtures and the floor is static while the falling object is dynamic.
  • Check that the shapes occupy the expected coordinates and that the world is being stepped.
  • Verify category and mask bits permit the pair to interact.
  • Check whether the fixture is a sensor when physical collision response was expected.
  • Look for code teleporting the dynamic body through the floor.

Callbacks appear to be missing or inconsistent

Confirm the listener belongs to the world being stepped and that the fixtures overlap, are active and pass filtering. A sensor can produce overlap callbacks without physical response. A contact callback is not a high-level event, fixture order is not a guarantee, and multiple fixtures may represent one entity. Track contacts by pair or maintain a count/set for states such as grounded.

Crash while destroying a body

The world may be locked during a simulation step or callback. Put the body or joint operation in a queue and execute it only after the step returns, as shown above.

Jitter or unstable motion

Check for a variable timestep, extreme scale or speed, complicated collision geometry, excessive restitution, interpenetrating spawn positions, too few solver iterations, or several movement systems fighting over the same body. Use a fixed timestep, simpler convex shapes and one authoritative movement path; increase solver iterations cautiously. Avoid repositioning dynamic bodies every frame as a substitute for normal motion.

Version and compatibility notes

The libGDX Java wrapper retains the familiar Box2D 2.x-style API around worlds, bodies, fixtures, contacts and joints. Upstream documentation is useful for concepts, but it does not map one-to-one to the Java binding: libGDX notes the API adaptations in its physics documentation, and upstream documentation itself cautions that its manual can lag code changes. See Box2D documentation and the upstream repository. The native wrapper requires platform packaging, while JBox2D avoids that JNI packaging path but is a distinct integration. Neither route should be treated as an automatic promise of cross-platform deterministic simulation; validate behavior on the targets you ship.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.