Created
December 30, 2019 14:24
-
-
Save mgsx-dev/ff693b8d83e6d07f88b0aaf653407e5a to your computer and use it in GitHub Desktop.
LibGDX Pixel perfect viewport that scale to integer fraction of your world
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.badlogic.gdx.math.MathUtils; | |
import com.badlogic.gdx.utils.viewport.FitViewport; | |
public class PixelPerfectViewport extends FitViewport { | |
public PixelPerfectViewport(float worldWidth, float worldHeight) { | |
super(worldWidth, worldHeight); | |
} | |
@Override | |
public void update(int screenWidth, int screenHeight, boolean centerCamera) { | |
// get the min screen/world rate from width and height | |
float wRate = screenWidth / getWorldWidth(); | |
float hRate = screenHeight / getWorldHeight(); | |
float rate = Math.min(wRate, hRate); | |
// round it down and limit to one | |
int iRate = Math.max(1, MathUtils.floor(rate)); | |
// compute rounded viewport dimension | |
int viewportWidth = (int)getWorldWidth() * iRate; | |
int viewportHeight = (int)getWorldHeight() * iRate; | |
// Center. | |
setScreenBounds((screenWidth - viewportWidth) / 2, (screenHeight - viewportHeight) / 2, viewportWidth, viewportHeight); | |
apply(centerCamera); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment