Sometimes you want that your game keeps the aspect ratio and that black borders appear. These borders are called letterbox.
I’m folliwing the idea of blog.arcamara.es.
I’m folliwing the idea of blog.arcamara.es.
First we have to define the screensize our game has:
Rectangle viewport;
float virtualWidth=800;
float virtualHeight=480;
float virtualAspectRatio=virtualWidth/virtualHeight;
In create() we create the camera and an rectangle for the part of the real window that is filled with the game.
camera=new OrthographicCamera(virtualWidth,virtualHeight);
viewport=new Rectangle();
In the resize()-method we calculate the size of the letterbox and set the viewport-rectangle accordingly.
@Override
public void resize(int width, int height) {
float aspectRatio=width/(float)height;
float scale=1;
float cropX=0;
float cropY=0;
// calculate scale and size of the letterbox
if(aspectRatio > virtualAspectRatio){
scale = (float)height/(float)virtualHeight;
cropX = (width - virtualWidth*scale)/2f;
}else if(aspectRatio < virtualAspectRatio){
scale = (float)width/(float)virtualWidth;
cropY = (height - virtualHeight*scale)/2f;
}else{
scale = (float)width/(float)virtualWidth;
}
// set the viewport
viewport.set(cropX,cropY,virtualWidth*scale,virtualHeight*scale);
}
In render() we have to change the viewport after cleaning the screen.
Gdx.gl.glClearColor(0,0,0, 1);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
// set viewport
Gdx.gl.glViewport((int) viewport.x, (int) viewport.y,
(int) viewport.width, (int) viewport.height);


Now the letterbox works, but we have a problem, if we want the touched position.
When projecting it to our screenspace we now have to pass the viewport. (In this example we as well check that the touch is not in the black borders).
if(Gdx.input.isTouched()){
if(Gdx.input.getX()>viewport.x&&Gdx.input.getX()<viewport.x+viewport.width&&Gdx.input.getY()>viewport.y&&Gdx.input.getY()<viewport.y+viewport.height){
Vector3 touchPos = new Vector3();
touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touchPos,viewport.x,viewport.y,viewport.width,viewport.height);
player.setXY(touchPos.x-player.getWidth()/2,touchPos.y-player.getHeight()/2);
}
}
No comments:
Post a Comment