Search code examples
javalibgdx

How do I draw a rectangular polygon without a triangular cutout?


I am creating a rectangular polygon that represents the box bounding the player sprite in a simple 2D game. This is the implementation I use:

float[] vertices = new float[] {player.getSprite().getX(), player.getSprite().getY(),
                player.getSprite().getX() + player.getSprite().getWidth(),
                player.getSprite().getY(), player.getSprite().getX(),
                player.getSprite().getY() + player.getSprite().getHeight(),
                player.getSprite().getX() + player.getSprite().getWidth(),
                player.getSprite().getY() + player.getSprite().getHeight()};

        Polygon rPoly = new Polygon(vertices);

        polyBatch.draw(
                new PolygonRegion(new TextureRegion(healthImage), rPoly.getTransformedVertices(),
                new EarClippingTriangulator().computeTriangles(vertices).toArray()),
                player.getSprite().getScaleX(), player.getSprite().getScaleY());

Where the "Sprite" is an actual LibGDX sprite object. When I try to use this implementation I get this as a result:

enter image description here

How do I get this polygon to be drawn without that triangular cut in it?


Solution

  • I will start this answer with a disclaimer: I have never used LibGDX before. Nonetheless I can see a potential problem with your code.

    Let's number the corners of your rectangle as follows:

       1         2
    
       3         4
    

    Your array of vertex coordinates includes these corners in the order 1, 2, 3, 4.

    You are using a polygon object to represent this rectangle. Polygon objects will typically expect the vertex coordinates that they are given to go around the polygon in one direction or the other. For example, if you had a polygon with 10 points, how would the Polygon class know in which order to connect the points? Of course, order 1, 2, 3, 4 is not going around your rectangle in either direction.

    Try swapping the order of the last two pairs of coordinates, so that your array of vertices includes the corners in the order 1, 2, 4, 3.


    Bonus hint for readability: try to format your array of vertices so that it contains one pair of coordinates per line, perhaps something like the following:

    Sprite sprite = player.getSprite();
    float[] vertices = new float[] {
        sprite.getX(),                     sprite.getY(),
        sprite.getX() + sprite.getWidth(), sprite.getY(),
        sprite.getX() + sprite.getWidth(), sprite.getY() + sprite.getHeight(),
        sprite.getX(),                     sprite.getY() + sprite.getHeight()
    };
    

    To reduce the line length, I've created a local variable for the value of player.getSprite(). I've guessed the name of the class as Sprite: feel free to adjust this if necessary. You could potentially create further local variables for the values of sprite.getX(), sprite.getY() and so on.