# How do I calculate the z-coordinate for a perspective-camera in 2D?

I'm new to LibGDX and trying to use `DecalBatch` with `PerspectiveCamera`, simply to have Z-coordinate for my sprites, as `SpriteBatch` does not offer that. However, I don't know how to calculate the Z-coordinate for the `PerspectiveCamera` for "pixel-perfect 2D-projection". How do I do that?

-
If you want pixel perfect don't you want an ortho camera? – Tetrad Mar 7 '13 at 16:57
But I'd really like my sprites to have the ability to be zoomed in and out in perspective.. simply by adjusting their z-position. And that's not possible with orthographic projection.. but from what I've gathered that's how DecalBatch and PerspectiveCamera works. Maybe pixel-perfect was a wrong word, I'd like to get the camera zoomed "at least roughly at the pixel size". – TX-256 Mar 7 '13 at 19:14
Obvious solution being why not compute the scale value from the z-position? Don't pick your camera based on how you want to do scaling. Pick it based on the visual you want to achieve. – ClassicThunder Oct 8 '14 at 17:12

What "Pixel perfect" is depends on the size of your textures divided by the mesh's area. First, It's important you keep the aspect ratio between your mesh and textures: If your texture is 64x32, your mesh/quad/Decal will be 2:1 (for example, 2x1).

Now, closer to what you desire, the most important part is to have a consistent and analogous unit measurement. Let's go back to the example before, but let's make the Decal 64x32 (we'll make the 3D unit be equivalent to a "pixel" -notice the quotes, as it's not really the case, just a illusion to help us-). Next, you have to calculate which depth/distance from the general decal plane (assuming your decal's will be coplanar, if not, you can't achieve "pixel perfect" on all -well, you can, but decals with the same resolution should be coplanar-) using the inverse of the equations exposed here: http://docs.unity3d.com/Documentation/Manual/FrustumSizeAtDistance.html (calculating the inverse will be left as exercise for you, or you can always iterate to aproximate)

And, with the distance calculated, you set the camera to look at the plane from that distance: Suposing a XY plane, set z=thisDistance You may need to toy around with the Field Of View depending on the resolution/aspect ratio, or you'll only achieve "Pixel Perfect" on a single dimension.

-

This is one area that I also found quite lacking. Instead of using `DecalBatch`, I did something much, much simpler: I added a `.z` value to all sprites, and just draw them in order.

Technically, I created my own wrapper/subclass of `Sprite` with a `z` property which I can get and set. When drawing, I have a sorted list of sprites, and just draw them from lowest- to highest-z.

In terms of performance, try to maintain the sorting/ordering outside of the actual drawing (don't re-sort on each draw call, only when you add/remove a sprite).

-