2
votes

I know how to apply sprite to a Box2d body, but is there a way to apply a texture to it? Basically what I am trying to do is to have one texture, let's say 32x32, and then just repeat it all over the body, like the ground in this image:

enter image description here

Is this possible in LibGDX?

EDIT:

My latest try:

Fixture fixture = body.createFixture(fixtureDef);
        Vector2 mTmp = new Vector2();
        PolygonShape shape = (PolygonShape) fixture.getShape();
        int vertexCount = shape.getVertexCount();
        float[] vertices = new float[vertexCount * 2];
        for (int k = 0; k < vertexCount; k++) {
            shape.getVertex(k, mTmp);
            mTmp.rotate(body.getAngle()* MathUtils.radiansToDegrees);
            mTmp.add(body.getPosition()); 
            vertices[k * 2] = mTmp.x * PIXELS_PER_METER;
            vertices[k * 2 + 1] = mTmp.y * PIXELS_PER_METER;
        }
        short triangles[] = new EarClippingTriangulator().computeTriangles(vertices).toArray();

        Texture texture = new Texture(Gdx.files.internal("data/block.png"));
        texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);

        TextureRegion textureRegion = new TextureRegion(texture, 0, 0, texture.getWidth(), texture.getHeight());
        
        PolygonRegion region = new PolygonRegion(textureRegion, vertices, triangles);
        
        poly = new PolygonSprite(region);

and in rendering:

polyBatch.begin();
        poly.draw(polyBatch);
        polyBatch.end();

but it doesn't draw anything.

After importing different shape of level, I get this result:

enter image description here

Only one polygon ( shown inside of red circle ) gets the texture. Whole level is imported as a JSON file

1

1 Answers

3
votes

Yes This is very much possible in libgdx.

You just need to create a polygon region for that

PolygonRegion region = new PolygonRegion(textureRegion, vertices, triangles);

Here textureRegion is the region that you want to repeat. vertices and triangles define the shape of the region.

This polygon region is a repeated texture that is form red from the vertices and triangles. You can render this region using polygon batch just same as we do it with sprite batch.

UPDATE

PolygonShape shape = (PolygonShape) fixture.getShape();
int vertexCount = shape.getVertexCount();
float[] vertices = new float[vertexCount * 2];
for (int k = 0; k < vertexCount; k++) {
    shape.getVertex(k, mTmp);
    mTmp.rotate(body.getAngle()* MathUtils.radiansToDegrees);
    mTmp.add(bodyPos); 
    vertices[k * 2] = mTmp.x * PIXELS_PER_METER;
    vertices[k * 2 + 1] = mTmp.y * PIXELS_PER_METER;
}
short triangles[] = new EarClippingTriangulator()
        .computeTriangles(vertices)
        .toArray();
PolygonRegion region = new PolygonRegion(
        textureRegion, vertices, triangles);