0
\$\begingroup\$

I am currently working on a racing game with libGDX and I need to split the screen in half for a two-players mode. (Player 1 in first half and Player 2 in second half).

I already have Camera1 that will follow Player 1's car, and Camera2 that will follow Player 2's car.

Basically, I want the first half to show Player 1's car and the second half to show Player 2's car.

I have been searching for a while online for a way to split screens with LibGDX and found how to split the screen in two with this code:

/*Left Half*/
Gdx.gl.glViewport( 0,0,Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight() );

/*Right Half*/
Gdx.gl.glViewport(Gdx.graphics.getWidth()/2,0,Gdx.graphics.getWidth()/2,Gdx.graphics.getHeight() );

However, it squeezes the screen into the right half, which is not what I want.

Is there a way to split the screen without squeezing it?

\$\endgroup\$
  • \$\begingroup\$ You could render both cameras in the same viewport. \$\endgroup\$ – nathan Apr 26 '16 at 18:57
1
\$\begingroup\$

I would suggest having a look at this page and using a viewport to manage both cameras. Since you don't want scaling a ScreenViewport would be the way to go.

https://github.com/libgdx/libgdx/wiki/Viewports

// These would be the cameras you have set up which are following the players
Camera playerOneCamera;
Camera playerTwoCamera;

ScreenViewport playerOneViewport = new ScreenViewport(playerOneCamera);
ScreenViewport playerTwoViewport = new ScreenViewport(playerTwoCamera);

Each time the window is resized you would update both viewports with new dimensions and offsets. To split the screen vertically you would do the following:

public void resize(int width, int height){
    playerOneViewport.update(width / 2, height);
    playerTwoViewport.update(width / 2, height);
    playerTwoViewport.setScreenX(width / 2);
}

Then each draw call you perform two renderings, one using the first cameras projection and another using the second cameras projection.

public void render(){
    // Set batch to use first players camera
    batch.setProjectionMatrix(playerOneCamera.combined);
    batch.begin();
    // Render what is required
    batch.end();

    // Set batch to use second players camera
    batch.setProjectionMatrix(playerTwoCamera.combined);
    batch.begin();
    // Render what is required
    batch.end();
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.