简体   繁体   中英

How to display a rotated polygon in ShapeRenderer LibGDX/Java

I am making a simple game but I don't seem to be able to rotate a simple polygon. I did a test below.

I have ( ShapeRenderer shape ) and ( shape = new ShapeRenderer() ) initialized above.

Below is my code.

    float x1 = 200;
    float y1 = 200;
    float x2 = 250;
    float y2 = 200;
    float x3 = 250;
    float y3 = 250;
    float x4 = 200;
    float y4 = 250;

    float[] f = {x1,y1,x2,y2,x3,y3,x4,y4};

    Polygon polygonTest = new Polygon();
    polygonTest.setVertices(f);
    polygonTest.setOrigin(x1+25,y1+25);
    polygonTest.rotate(-45f);

    shape.begin(ShapeRenderer.ShapeType.Line);
    shape.polygon(polygonTest.getVertices());
    shape.end();

This is the output

After rotation, I double check its rotation value using polygonTest.getRotation() and it returns the correct value. I have also tried positive values without the "f" (float) indicator in the parameter but no luck.

All the threads I have read about this particular issue just mentioned to setOrigin then rotate, but it is not working for me.

Any help is appreciated!

getVertices() method of Polygon returns the polygon's local vertices without scaling or rotation.

Use getTransformedVertices() that returns the vertices of the polygon after scaling, rotation.

Here is Test Code :

public class GdxTest extends ApplicationAdapter {

    ShapeRenderer shapeRenderer;
    Polygon polygonTest;

    @Override
    public void create() {

        shapeRenderer= new ShapeRenderer();

        float x1 = 200;
        float y1 = 200;
        float x2 = 250;
        float y2 = 200;
        float x3 = 250;
        float y3 = 250;
        float x4 = 200;
        float y4 = 250;

        float[] f = {x1,y1,x2,y2,x3,y3,x4,y4};

        polygonTest = new Polygon();
        polygonTest.setVertices(f);
        polygonTest.setOrigin(x1+25,y1+25);
        polygonTest.rotate(-45f);
    }

    @Override
    public void render() {

        Gdx.gl.glClearColor(0,0,0,1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        if (polygonTest.getRotation()<360){
            polygonTest.setRotation(polygonTest.getRotation()+1);
        }else
            polygonTest.setRotation(0);

        shapeRenderer.begin(ShapeRenderer.ShapeType.Line);
        shapeRenderer.polygon(polygonTest.getTransformedVertices());
        shapeRenderer.end();
    }

    @Override
    public void dispose() {
        shapeRenderer.dispose();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM