How do I zoom in and out of the stage in libgdx Scene2d?… here is a solution to the problem.
How do I zoom in and out of the stage in libgdx Scene2d?
I’m making a 2d game using libgdx and adding hexagonal actors to a group and then adding them to the stage. For normal cameras, you can use camera.zoom
in and out in the rendering method, while using camera.translate
to travel the world.
I’ve been using stage.getCamera() to get the
camera used on the stage, and I can still call stage.getcamera().translate but without the stage.getCamera().zoom
option.
Here is my code :
//import statements
public class HexGame implements ApplicationListener{
private Stage stage;
private Texture hexTexture;
private Group hexGroup;
private int screenWidth;
private int screenHeight;
@Override
public void create() {
hexTexture = new Texture(Gdx.files.internal("hex.png"));
screenHeight = Gdx.graphics.getHeight();
screenWidth = Gdx.graphics.getWidth();
stage = new Stage(new ScreenViewport());
hexGroup = new HexGroup(screenWidth,screenHeight,hexTexture);
stage.addActor(hexGroup);
}
@Override
public void dispose() {
stage.dispose();
hexTexture.dispose();
}
@Override
public void render() {
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
handleInput();
stage.getCamera().update();
}
private void handleInput() {
if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
stage.getCamera().translate(-3, 0, 0);
}
if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
stage.getCamera().translate(3, 0, 0);
}
if (Gdx.input.isKeyPressed(Input.Keys.DOWN)) {
stage.getCamera().translate(0, -3, 0);
}
if (Gdx.input.isKeyPressed(Input.Keys.UP)) {
stage.getCamera().translate(0, 3, 0);
}
This is the part that doesn't work
/*
if (Gdx.input.isKeyPressed(Input.Keys.Z)) {
stage.getCamera().zoom += 0.02;
}
*/
}
@Override
public void resize(int width, int height) {
stage.getViewport().update(width, height);
}
@Override
public void pause() {
}
@Override
public void resume() {
}
}
Thanks for any help, please let me know if I have any other issues with my code, I’m new to libgdx. Thanks
Solution
Scaling is available in the OrthographicCamera
class, which by default creates an
OrthographicCamera
/** Creates a stage with a {@link ScalingViewport} set to {@link Scaling#stretch}. The stage will use its own {@link Batch}
* which will be disposed when the stage is disposed. */
public Stage () {
this(new ScalingViewport(Scaling.stretch, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), new OrthographicCamera()),
new SpriteBatch());
ownsBatch = true;
}
Therefore, you need to convert the camera to OrthographicCamera
:
((OrthographicCamera)stage.getCamera()).zoom += 0.02f;