vtni vtni - 1 year ago 295
Java Question

Drawing filled polygon with libgdx

i wanted to draw some (filled) polygons with libgdx for an android game. it shoudn't be filled with a graphic/texture. i have only the vertices of the polygon (closed path) and tried to visualize with meshes but at some point this is not the best solution, i think.

my code for an rectangle is:

private Mesh mesh;
public void create() {
if (mesh == null) {
mesh = new Mesh(true, 4, 0,
new VertexAttribute(Usage.Position, 3, "a_position")
mesh.setVertices(new float[] { -0.5f, -0.5f, 0
0.5f, -0.5f, 0,
-0.5f, 0.5f, 0,
0.5f, 0.5f, 0 });

public void render() {
mesh.render(GL10.GL_TRIANGLE_STRIP, 0, 4);

is there a function or something to draw filled polygons in an easier way?

Answer Source

Here is a LIBGDX example which draws 2D concave poly.

// define class members for PolygonSprite PolygonSpriteBatch

PolygonSprite poly;
PolygonSpriteBatch polyBatch;
Texture textureSolid;

// create instances, 1x1 size texture used with red pixel as workaround, (x,y) array of coords used for initialization of poly

ctor() {
    textureSolid = makeTextureBox(1, 0xFFFF0000, 0, 0); 
    float a = 100;
    float b = 100;
    PolygonRegion polyReg = new PolygonRegion(new TextureRegion(textureSolid),
      new float[] {
        a*0, b*0,
        a*0, b*2,
        a*3, b*2,
        a*3, b*0,
        a*2, b*0,
        a*2, b*1,
        a*1, b*1,
        a*1, b*0,
    poly = new PolygonSprite(polyReg);
    poly.setOrigin(a, b);
    polyBatch = new PolygonSpriteBatch();

// draw and rotate poly

void draw() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download