8

Can any of you please demonstrate a simple example on how to use groups in libGdx ? so if i move the parent, then all the children will move with it and same goes for rotation and scaling.

I looked for tutorials and example online but it seems that the latest version of libGdx did some changes to the Stage class.

Thank you

alaslipknot
  • 472
  • 6
  • 18

1 Answers1

5

Here is exactly what i needed to have, this class allow to create 3 images and rotate them as they are a single object, thank you all for your inputs.

public class LearnGdx extends ApplicationAdapter {

    public static final int WIDTH = 800;
    public static final int HEIGHT = 480;

    private Stage stage;
    private Group group;

    private float rotSpeed = 5;

    @Override
    public void create() {

        // Create a stage
        stage = new Stage(new StretchViewport(WIDTH, HEIGHT));

        // Create a group and add it to the stage.
        group = new Group();
        stage.addActor(group);

        // Create images and add them to the group.
        final Texture region = new Texture(Gdx.files.internal("circle.png"));
        Image img = new Image(region);
        Image img2 = new Image(region);
        Image img3 = new Image(region);

        img2.setColor(new Color(1, 0, 0, 1));
        img3.setColor(new Color(0, 0, 1, 1));

        group.addActor(img2);
        group.addActor(img3);
        group.addActor(img);

        // Images are positioned relative to the group...
        img.setPosition(0, 0);
        img2.setPosition(img.getWidth()/2, 0);
        img3.setPosition(-img.getWidth()/2, 0);

        // Group is positioned relative to the stage...
        group.setPosition(WIDTH / 2 - img.getWidth() / 2,
            HEIGHT / 2 - img.getHeight() / 2);
        group.setOrigin(img.getWidth()/2,img.getHeight()/2);

    }

    @Override
    public void render() {
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        stage.act(Gdx.graphics.getDeltaTime());
        stage.draw();

        if (Gdx.input.isKeyPressed(Keys.LEFT)) {
            group.rotateBy(rotSpeed);
        }
        if (Gdx.input.isKeyPressed(Keys.RIGHT)) {
            group.rotateBy(-rotSpeed);
        }
    }
}
topher
  • 103
  • 3
alaslipknot
  • 472
  • 6
  • 18