I previously used SFML, XNA, Monogame, etc. to create 2d games, where if I display a 100px sprite on the screen, it will take up 100px. If I use 128px tiles to create a background, the first tile will be at (0, 0) while the second will be at (128, 0).
Unity on the other hand, has its own odd unit system, scaling on all transforms, pixel-to-units, othographic size, etc, etc. So my question is two-fold, namely:
- Why does Unity have this system by default for 2d? Is it for mobile dev? Is there a big benefit I'm not seeing?
- How can I setup my environment, so that if I have a 128x128 sprite in Photoshop, it displays as a 128x128 sprite in Unity when I run my game?
Note that I am targeting desktop exclusively.
Answer
Handling 2D coordinates and scaling in Unity is fairly simple, but non-obvious and as you've noticed it's unlike how other dev tools work. Why this happens is because Unity was a 3D engine that recently had 2D graphics grafted in.
In particular, 1 unit in Unity is not necessarily 1 pixel in the image. When you import images as 2D Sprites there's actually a Pixels-to-Units setting that could be made 1:1 but I recommend leaving it at the default 100:1 for a couple reasons (the physics engine doesn't work right at 1:1, and the default is better for compatibility with others' code).
This scaling setting means that all positions are divided by 100. It's pretty easy as long as you always remember the scaling; when you want to move a sprite 256 pixels (say) then you move it 2.56 You may also want to write a utility function to round numbers to 2 decimal places/the nearest pixel: Mathf.Round(float * 100) / 100f
As for setting up a pixel-perfect camera, first off set it as an orthographic camera. When you select the camera, in it's settings is a drop-down for Perspective or Orthographic projection; perspective means things will look 3D, while orthographic displays the scene flat. Right under this drop-down is Size; set the camera's orthographic size to half the pixel dimensions of the screen you want.
For example, let's say you want a pixel-perfect 1024x768 screen. Well that means the camera height should be 384 pixels. Divide that by 100 (because of the pixels-to-units scale) and you get 3.84 for the camera size. Again, that math is simply SCREEN_SIZE / 2 / 100f
(I was waiting to see what other answers come first, but it's been a couple days. I've been doing 2D in Unity for a while using 2D Toolkit, but am relatively new to the built-in 2D features)
No comments:
Post a Comment