- Home /
How to position and scale an element based on the aspect ratio?
I have UI elements positioned in the correct places on a 16:9 aspect ratio. I would like to make these elements automatically reposition and scale on start to match the aspect ratio, being that I will need them to work on multiple platforms.
Edit: The elements are simply GameObjects. As far as anchor points, they do not touch the sides of the screen necessarily but I would like them anchored to one of the sides, depending on the placement of the element.
You may need to be more specific to get your answer(s). The solution will depend on the kind of object(world object, GUITExture/GuiText, GUI.* class calls), and how you want to define your anchor points. This issue has been covered a number of times on UA, but usually the answer is specific to the OP situation.
Orthographic or Perspective camera? I assume all the elements will be the same distance from the camera?
Answer by robertbu · Mar 14, 2014 at 10:38 PM
For a world object, the easiest solution is to make all your visible object a child of an empty game object. The empty game object is placed at the anchor point, and all anchor points will be places on some edge(s) of the screen. If you want the visible object to stand off the edge by a bit, you can just place the anchor a bit outside the object.
To place the object, you can use Viewport coordinates. Viewport coordinates go from (0,0) in the lower left corner to (1,1) in the upper right. So if you had an object with an anchor point in the lower right that you wanted to anchor to the lower left corner of the screen you could this with a script on the anchor object:
function Start() {
transform.position = Camera.main.ViewportToWorldPoint(Vector3(1.0,0,dist));
}
For a perspective camera, 'dist' will be the distance on the local 'z' axis the objects is away from the camera. For exmaple if your camera was at -10 on the 'z' axis, and the object to be position as at 1 on the 'z' axis, dist would be 11. For an Orthographic camera, you can ignore 'dist' or just overwrite the 'z' parameter that comes out of the ViewportToWorldPoint() call.
If you wanted to anchor to the bottom middle, you would place the anchor object in the bottom middle of your visible object and use (0.5,0,dist) in the ViewportToWorldPoint(). And so on.