Box2D for libGDX Game Development

Keywords: Java Game Development

Box2D (14) for libGDX Game Development
LibGDX series, game development has unity3D Barabara, why use Java development? Because I'm a Java programmer, emm... I use libgdx less domestically. In most cases, I need to go to the official website and google to find information. If I learn from each other, I can contact you.
Official description of libgdx:

Box2D is a two-dimensional physical library. It is one of the most popular physical libraries for 2D games and has been ported to many languages and many different engines, including libGDX. The Box2D implementation in libGDX is a thin Java wrapper around the C++ engine.

It is known that the Box2d base of libgdx calls Box2d C++. Instantly encapsulating it, the official website also describes the use of Box2D as basically consistent with the C++ document description: https://box2d.org/
Documentation of Box2d's use of libgdx: https://github.com/libgdx/libgdx/wiki/Box2d
However, there are many unclear descriptions in practice, especially the gravity phenomenon of the object is not obvious under normal pixels, the texture needs to be reduced by 100++ times to have a more obvious physical effect. Use the following steps:

1. Create a world with gravity and objects inside
2. Use the Box2DDebugRenderer as a renderer to help us outline Box2d objects so that we can easily see where they are and how big they are. It needs to be commented on in a formal game.
3. Use: Create Body: Static objects (ground, wall), dynamic objects (players, monsters), moving objects ()

Box2DDebugRenderer

It is worth mentioning that Box2DDebugRenderer has the following effects:

Observing lines and frames is how it works.

1. Write a simple demo

It should also be mentioned that the phenomenon of gravity is not obvious in normal pixels, and the texture needs to be reduced by 100++ times to have a more obvious physical effect.
Of course, you can also explore for yourself. Here are my demo effects:

The code is as follows

import com.badlogic.gdx.ApplicationAdapter;
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.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.*;

/**
 * @author lingkang
 */
public class MyBox2D extends ApplicationAdapter {
    private SpriteBatch batch;
    private TextureRegion img, dog;
    private OrthographicCamera camera;

    private World world;
    private Box2DDebugRenderer debugRenderer;
    private Body dogBody;
    // The gravity of the object is not obvious in normal pixels, and the texture needs to be reduced by 100++ times to have a more obvious physical effect.
    private float reduce = 100;// Reduce by 100 times to easily observe physical phenomena
    private boolean isJump;

    @Override
    public void create() {
        batch = new SpriteBatch();
        // Create a camera where you can zoom out 64 times because the object you're looking at needs to be 100 times smaller
        camera = new OrthographicCamera();
        camera.setToOrtho(false, Gdx.graphics.getWidth() / 64, Gdx.graphics.getHeight() / 64);

        // Picture 1: A 100-fold reduction of 50*50 means a 0.5*0.5 reduction in drawing time
        dog = new TextureRegion(new Texture("dog.jpg"), 50, 50);
        // Picture 2: 256*256...
        img = new TextureRegion(new Texture("badlogic.jpg"), 256, 256);

        // Create a world where the acceleration of gravity is 10
        world = new World(new Vector2(0, -10), true);
        // Trial rendering, which can be used to observe the object graphics we draw with Box2D
        debugRenderer = new Box2DDebugRenderer();

        // Creating a ground is actually a static object, here we call it the ground, on which players can walk
        BodyDef groundBodyDef = new BodyDef();
        groundBodyDef.type = BodyDef.BodyType.StaticBody;// Static mass is 0
        groundBodyDef.position.x = 0;// position
        groundBodyDef.position.y = 0;
        // Create the body of this ground, and we treat this object
        Body groundBody = world.createBody(groundBodyDef);
        PolygonShape groundBox = new PolygonShape();// The shape of the object so that it is rectangular
        groundBox.setAsBox(Gdx.graphics.getWidth(), 10);// Width and height of object
        groundBody.createFixture(groundBox, 0); // Mass of static objects should be set to 0

        // Create a static object that we can think of as an obstacle
        BodyDef badlogicBodyDef = new BodyDef();
        badlogicBodyDef.type = BodyDef.BodyType.StaticBody;
        badlogicBodyDef.position.x = 10;
        badlogicBodyDef.position.y = 10 + 1.28f; // + 1.28 because pictures drawn from the center can also be written as +256/2/100
        Body badlogicBody = world.createBody(badlogicBodyDef);
        PolygonShape badlogicBox = new PolygonShape();
        badlogicBox.setAsBox(256 / 2 / reduce, 256 / 2 / reduce);// Graphics are drawn by the center, so divide by half
        badlogicBody.createFixture(badlogicBox, 0); // Mass of static objects should be set to 0

        // Add another dynamic object to consider it a player
        BodyDef dogBodyDef = new BodyDef();
        dogBodyDef.type = BodyDef.BodyType.DynamicBody;
        dogBodyDef.position.x = 10;
        dogBodyDef.position.y = 20;
        dogBody = world.createBody(dogBodyDef);
        PolygonShape dynamicBox = new PolygonShape();
        dynamicBox.setAsBox(50 / 2 / reduce, 50 / 2 / reduce);

        // Add some attributes to the object
        FixtureDef fixtureDef = new FixtureDef();
        fixtureDef.shape = dynamicBox;// shape
        fixtureDef.restitution = 0.2f; // When this value is set, the object falls to the ground and it will pop up a little bit high...
        dogBody.createFixture(fixtureDef).setUserData(this);//Set custom data to get this data object from this object

        // To get rid of the above graphics
        groundBox.dispose();
        dynamicBox.dispose();
    }

    @Override
    public void render() {
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        // Get the position of the object
        Vector2 position = dogBody.getPosition();

        // Bind Camera to Batch Wizard
        camera.position.set(position.x, position.y, 0);
        camera.update();

        // Key to binding drawing to camera projection
        batch.setProjectionMatrix(camera.combined);
        batch.begin();
        batch.draw(img, 10 - 1.28f, 10, 0, 0, 256, 256, 0.01f, 0.01f, 0);
        batch.draw(dog, position.x - 50 / 2 / reduce, position.y - 50 / 2 / reduce, // Set position to be reduced by 50/2/reduce to coincide with the shape of the object
                0, 0, 50, 50, // Draw a part of the picture, this is all
                1 / reduce, 1 / reduce, // 100 times smaller
                0 // No Rotation
        );
        batch.end();

        // Get Linear Speed of Five Stars
        Vector2 linearVelocity = dogBody.getLinearVelocity();
        if (Gdx.input.isKeyPressed(Input.Keys.D) && linearVelocity.x <= 2) { // Now the maximum speed is 2, or you'll set yourself free
            // Applying an impulse to make the object run can be seen as we push it and move it aside
            dogBody.applyLinearImpulse(new Vector2(0.1f, 0), dogBody.getWorldCenter(), true);
        }
        if (Gdx.input.isKeyPressed(Input.Keys.A) && linearVelocity.x >= -2) {
            dogBody.applyLinearImpulse(new Vector2(-0.1f, 0), dogBody.getWorldCenter(), true);
        }

        // The logic to jump up is simpler. But time for this demonstration
        if (!isJump && Gdx.input.isKeyPressed(Input.Keys.W) && linearVelocity.y <= 4) {
            dogBody.applyLinearImpulse(new Vector2(0, 4), dogBody.getWorldCenter(), true);
            isJump = true;
        }
        if (linearVelocity.y == 0) {
            isJump = false;
        }

        // Draw outlines of objects in the Box2D world so that we can see them more clearly. Formal games need to comment out this rendering
        debugRenderer.render(world, camera.combined);

        // Renew relationships in the world after drawing, preferably at the end
        world.step(1 / 60f, 6, 2);
    }
}
/**
 * @author lingkang
 */
public class MyBox2DApplication {
    public static void main(String[] args) {
        LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
        new LwjglApplication(new MyBox2D(), config);
    }
}

Posted by creatives on Sun, 24 Oct 2021 09:44:29 -0700