Search code examples
javalibgdx

How do you move shapes in LibGDX?


I am currently trying to move a shape using an arrow key press in LibGDX. This is what I have so far:

    shapeRenderer.setColor(Color.BLACK);
    shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
    shapeRenderer.rect(250,250,20,20);
    if(Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
        shapeRenderer.rect(200,250,20,20);

    }
    shapeRenderer.end()

However it seems to only create a new shape, as opposed to move my old one. Is there a way to move the old one with shapes, or should I be using another class?


Solution

  • ShapeRenderer only renders points, lines, "shapes" that you tell it to draw. It doesn't actually store/create shapes itself. Your code renders a rectangle every time, and if the Left key is pressed will simply draw a 2nd rectangle at slightly different coords.

    If you simply want to use shapes, look at the libGDX Rectangle class itself (there are also Circle, Ellipse, Polygon classes). You can create a rectangle (assign x/y coords, width/height, etc) and then use the shape renderer to draw that rectangle based on the rectangle's x/y coords (or width/height/etc).

    That's a simplistic solution, but may be all you need