Search code examples
javalibgdx

How do I use an image as sprite in libGDX?


I used the following code to draw a circle in my world. Now I want to replace it with an single image, but I have no idea how to do that.

public void definePlayer() {
        BodyDef bodyDef = new BodyDef();
        bodyDef.position.set(32 / MyProject.PPM, 32/MyProject.PPM);
        bodyDef.type = BodyDef.BodyType.DynamicBody;
        body = world.createBody(bodyDef);

        FixtureDef fixtureDef = new FixtureDef();

        CircleShape shape = new CircleShape();
        shape.setRadius(5 / MyProject.PPM);

        fixtureDef.shape = shape;
        body.createFixture(fixtureDef);
    }

I followed this tutorial series and I understand much of it, but this episode leaves question marks in my head.


Solution

  • What you are using now to draw your physical objects, is actually a debug renderer. It is a tool to make you physical simulation visible. And it is not used for "actual" rendering.

    Physical simulation is, and also should be separated from rendering.

    So in order to make your object to look like a real thing, you have to render your image(sprite) with the same location and rotation and scale as your physical square. That way your image will copy movement of your physical object and will create a illusion of a real looking object.

    I would highly suggest you to read official documentation, which I think is the best place to learn about libGDX.

    Also look under "SpriteBatch, TextureRegions, and Sprites" tab, where you can read more about how to render stuff.