user3690202
user3690202

Reputation: 4045

How to limit where a camera renders to onscreen in LibGDX

I have a camera set up in LibGDX which draws what is a HUD-like layer of buttons and status. In the middle of this, I want a block of text, which could be longer than the screen, so I want to be able to pan around it using gestures.

I was thinking, the way to do this would be to define a second camera, with an large viewport, i.e.:

    textCamera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
    textCamera.setToOrtho(true, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());

And then apply it to my batch before writing out the bulk of the text. However, how can I restrict it such that this textCamera will only ever draw contents to the screen between, say, (0, 100) -> (600, 800). In this case the screen width, just for example, is 600 wide, and the height is maybe 1000 so I want to leave a gap at the top and bottom.

So, basically I want a big viewport, write all text out to viewport, be able to view it at 1:1 scale, but also be able to pan around the text. Just like you do when you pan up and down a website while surfing on an Android.

Upvotes: 1

Views: 407

Answers (2)

P.T.
P.T.

Reputation: 25177

I think you want a scissor stack? This lets you define a rectangular sub-region of the display to render to, and only pixels inside that rectangle will be rendered.

Upvotes: 1

m.antkowicz
m.antkowicz

Reputation: 13571

You should create second stage for a HUD and then add to it ActorGestureListener with defined pan method. You can easily control its camera position by checking if the position is not bigger/lower than some value in the method.

    Stage hudStage; //create it with even the same viewport as stage and add to it all hud's actors

    ...

    hudStage.addListener(aListener);

    ...

    final float MAX_X = 100, MIN_X = -100, MAX_Y = 100, MIN_Y = -100;

    ActorGestureListener aListener = new ActorGestureListener()
    {
        @Override
        public void pan(InputEvent event, float x, float y, float deltaX, float deltaY)
        {
            //if you want to move slower you can divide deltaX and deltaY by some value like:
            //deltaX /= 5f;

            if( stage.getCamera().position.x + deltaX < MAX_X && stage.getCamera().position.x + deltaX > MIN_X  )
            {
                stage.getCamera().position.x += deltaX;
            }


            if( stage.getCamera().position.y + deltaY < MAX_Y && stage.getCamera().position.y + deltaY > MIN_Y  )
            {
                stage.getCamera().position.y += deltaY;
            }
        }
    };

Upvotes: 1

Related Questions