I have a hexagon-shaped polygon. I want to put a part of a rectangular image onto it (a part because it's a hexagon, not a rectangle). I tried to do this using PolygonRegion, but it gives a weird and flipped result. Also when I have multiple hexagons, the texture is only on the first hexagon, and on the others, only the weird lines are visible. I use libGDX with the Game and Screen classes. I'd also like to know what this error/effect is called.
My questions:
- How do I make the texture scale to the size of the hexagon?
- How do I not flip the texture?
My (altered) code "GameScreen":
class GameScreen implements Screen {
private OrthographicCamera cam;
private PolygonSpriteBatch pSB;
private Hexagon hexagon1, hexagon2;
public final int HEXAGON_WIDTH = 100;
public final int HEXAGON_HEIGHT = (int) (HEXAGON_WIDTH / (Math.sqrt(3) / 2));
//Ratio of width and height of a regular hexagon.
GameScreen() {
this.cam = new OrthographicCamera(800, 800);
cam.setToOrtho(true);
cam.position.set(cam.viewportWidth / 2f, cam.viewportHeight / 2f, 0);
cam.update();
hexagon1 = new Hexagon(new Vector2(0, 0));
hexagon2 = new Hexagon(new Vector2(HEXAGON_WIDTH + 2, 0));
pSB = new PolygonSpriteBatch();
}
@Override
public void render(float delta) {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
Gdx.gl.glClearColor(1, 1, 1, 1);
cam.update();
pSB.setProjectionMatrix(cam.combined);
pSB.begin();
hexagon1.draw(pSB);
hexagon2.draw(pSB);
pSB.end();
}
}
Class Hexagon
class Hexagon {
private PolygonSprite sprite;
private Vector2 pos;
Hexagon(Vector2 pos) {
this.pos = pos;
this.sprite = createPolygonSprite();
}
private PolygonSprite createPolygonSprite() {
int hexWidth = GameScreen.HEXAGON_WIDTH;
int hexHeight = GameScreen.HEXAGON_HEIGHT;
float[] vertices = {
pos.x + hexWidth / 2, pos.y,
pos.x + hexWidth, pos.y + hexHeight * .25f,
pos.x + hexWidth, pos.y + hexHeight * .75f,
pos.x + hexWidth / 2, pos.y + hexHeight,
pos.x, pos.y + hexHeight * .75f,
pos.x, pos.y + hexHeight * .25f
};
PolygonRegion polygonRegion = new PolygonRegion(
new TextureRegion(new Texture(Gdx.files.internal("badlogic.jpg")),
vertices,
new EarClippingTriangulator().computeTriangles(vertices).toArray());
PolygonSprite polygonSprite = new PolygonSprite(polygonRegion);
polygonSprite.setOrigin(pos.x + width / 2, pos.y + height / 2);
return polygonSprite;
}
void draw(PolygonSpriteBatch pSB) {
this.sprite.draw(pSB);
}
}
The result (using similar code as written above but with more hexagons and other things):
What I expected to see (instead of the above picture): I expected to see the image not flipped and on every hexagon. The image should have been of such a size that all the hexagon space is filled (that of course means you can't see the corners of the image, but that's what I want). The image should be displayed on each hexagon, so it should start drawing on each hexagon. The image should scale to the size of the hexagon.