How to draw on just a portion of the screen with SpriteBatch in libgdx?

前端 未结 4 1632
-上瘾入骨i
-上瘾入骨i 2021-01-23 07:53

When I do this:

SpriteBatch spriteBatch = new SpriteBatch();
spriteBatch.setProjectionMatrix(new Matrix4().setToOrtho(         


        
4条回答
  •  日久生厌
    2021-01-23 08:26

    Before rendering the batch, you can set the viewport to draw on a specific screen area. The important line is:

    Gdx.gl.glViewport(x, y, w, h);
    

    The viewport usually starts at x = 0 and y = 0 and extends to the full width and height of the screen. If we want to see only a part of that original viewport, we need to change both the size and the starting position. To draw only on the left half of the screen, use:

    x = 0;
    y = 0;
    w = Gdx.graphics.getWidth()/2;
    h = Gdx.graphics.getWidth();
    

    I found the solution here and originally answered this question to a slightly more complicated problem, but the technique is the same.

    To focus on any different portion of the viewport, simply choose x, y, w, and h accordingly. If you're going to do any more rendering in the normal fashion, make sure to reset the viewport with the original x, y, w, and h values.

提交回复
热议问题