Cool things about OrthographicCamera
My last post for today is dedicated to the OrthographicCamera. Why would I dedicate a post to a class? Well, it turns out that you can make clever things with this class if you know how.
OrthographicCamera 101: Using cameras you can control the viewport of your game. Things like zoom, panning and such can be easily handled using cameras. You use cameras when you create a SpriteBatch (even if you don't, libGDX creates a camera for you). You use cameras when you create Scene2D stages (even if you don't, libGDX creates a SpriteBatch for you).
One of the methods, `setToOrtho`, let's you define the viewport of your screen. Then, the viewport is scaled to fit inside the screen. So, as an example, if you make your viewport 320x240 and your screen is 1280x720, the viewport is scaled to fit in the screen unless you change that.
This introduces something funny. In SpriteBatch, the units used by the draw() method aren't screen units, they are viewport units. This means, that if your viewport is 30x20 and you do
batch.draw(texture, 29, 19, 1, 1)
You'll get your texture on the upper right corner of the screen, even if your screen is 1280x720, because the batch is using viewport units.
How does this fit into a tiled map? Usually all of your tiles have the same width and the same height (sometimes even width == height).
If you set your viewport size to your screen size divided by your tile size, you can make your viewport units to be tiles!!!
So, for example, say that I want to fit 30x20 tiles on my window. I could do:
camera.setToOrtho(false, 30, 20)
Do you want to draw a texture over the tile 3x4? Just do:
batch.draw(texture, 3, 4)
Of course, if your viewport aspect ratio is not the same as your screen aspect ratio, you will get a very bad looking game, but if you play nicely with that, you will get great results.
I have tried to work in the past with tile systems and I always dealed with multiplying pixels per tiles because I didn't know this cool trick. Now that I know... phew! what a waste of time I have just avoided, don't you think?