- Home /
Positioning according to aspect ratio
Hi, in my game I decided to go for a 3d hud, now I'm having a problem, how can I make always fit the screen, I've set the position for the hud elements relative to the smallest aspect ration in the unity editor (5:4) so it's fitting perfectly for that aspect ratio, but if I go to 16:9 the hud will be way too much in the center.
To make things easier, I decided to separate the right hud elements from the left hud elements, (in different empty game objects), and the objects shall move along only the x axis depending on screen ratio. I have no idea how I can do this, could anyone help me getting this done?
Thanks in advance.
Answer by Scribe · Apr 12, 2014 at 05:45 PM
Okay so this (possible) solution will not resize your elements => no stretching. But will reposition them based on an anchor point of the screen and an offset.
To Use:
You would attach one instance of this script to each HUD element you have (lower left HUD element would be separate from upper left HUD element) You should call the 'Align' method as is done in the start function if the screen resolution is changed, you ~could~ call it from Update but that would be very inefficient (you might want to do this during testing to get the right positioning) so its preferable to check when the user changes resolution and then recalculate.
The rest is pretty self explanatory, choose an anchor from the drop down and possibly set an offset from that point, which should work as long as you have a MeshFilter attached to your HUD element and are using the main camera.
Code:
enum Alignment{
UpperLeft = 0,
UpperCenter = 1,
UpperRight = 2,
MiddleLeft = 3,
MiddleCenter = 4,
MiddleRight = 5,
LowerLeft = 6,
LowerCenter = 7,
LowerRight = 8
}
var alignment : Alignment = 0;
var offset : Vector2 = Vector2.zero;
private var mesh : Mesh;
private var min : Vector3;
private var max : Vector3;
private var center : Vector3;
function Start(){
mesh = GetComponent(MeshFilter).mesh;
min = mesh.bounds.min;
max = mesh.bounds.max;
center = mesh.bounds.center;
Align(alignment, offset);
}
function Align(i : int, off : Vector2){
var camTransform : Transform = camera.main.transform;
var dist : float = Vector3.Project((camTransform.position-transform.position), camTransform.forward).magnitude;
var screenPos : Vector3 = Vector3(0, 0, dist);
var worldOffset : Vector3 = Vector3.zero;
switch(i){
case 0:
screenPos.x = 0 + off.x;
screenPos.y = Screen.height + off.y;
worldOffset.x = (center.x - min.x);
worldOffset.y = (center.y - max.y);
break;
case 1:
screenPos.x = parseFloat(Screen.width)/2.0 + off.x;
screenPos.y = Screen.height + off.y;
worldOffset.x = 0;
worldOffset.y = center.y - max.y;
break;
case 2:
screenPos.x = Screen.width + off.x;
screenPos.y = Screen.height + off.y;
worldOffset.x = (center.x - max.x);
worldOffset.y = center.y - max.y;
break;
case 3:
screenPos.x = 0 + off.x;
screenPos.y = parseFloat(Screen.height)/2.0 + off.y;
worldOffset.x = (center.x - min.x);
worldOffset.y = 0;
break;
case 4:
screenPos.x = parseFloat(Screen.width)/2.0 + off.x;
screenPos.y = parseFloat(Screen.height)/2.0 + off.y;
worldOffset.x = 0;
worldOffset.y = 0;
break;
case 5:
screenPos.x = Screen.width + off.x;
screenPos.y = parseFloat(Screen.height)/2.0 + off.y;
worldOffset.x = (center.x - max.x);
worldOffset.y = 0;
break;
case 6:
screenPos.x = 0 + off.x;
screenPos.y = 0 + off.y;
worldOffset.x = (center.x - min.x);
worldOffset.y = center.y - min.y;
break;
case 7:
screenPos.x = parseFloat(Screen.width)/2.0 + off.x;
screenPos.y = 0 + off.y;
worldOffset.x = 0;
worldOffset.y = center.y - min.y;
break;
case 8:
screenPos.x = Screen.width + off.x;
screenPos.y = 0 + off.y;
worldOffset.x = (center.x - max.x);
worldOffset.y = center.y - min.y;
break;
}
transform.position = camera.main.ScreenToWorldPoint(screenPos);
transform.localPosition += worldOffset;
}
Hopefully that's of use!
Scribe
var alignment : Alignment = 0? what is that? I'm using c#, is it supposed to be a float?
its of my enum type Alignment defined right at the start, I don't use c# much but you should be able to do:
Alignment alignment = 0;
Almost rid of all conversion errors (I hope), now all erros are like this one:
The name `parseFloat' does not exist in the current context
edit: your script uses meshes, in my hud, I have an empty gameobject for the right bottom side of the hud, and inside that object there are the the meshes and text$$anonymous$$eshes already aligned to each other, so I would prefer to change the empty gameObject's position ins$$anonymous$$d, anyway, tried the script and it works (Tried the js version since I couldn't convert to c# yet)
Ahh if you already have everything aligned in an object you can miss out all the worldOffset stuff, heres an updated C# version (sorry if you've already finished your own conversion):
public enum Alignment{
UpperLeft = 0,
UpperCenter = 1,
UpperRight = 2,
$$anonymous$$iddleLeft = 3,
$$anonymous$$iddleCenter = 4,
$$anonymous$$iddleRight = 5,
LowerLeft = 6,
LowerCenter = 7,
LowerRight = 8
}
public Alignment alignment = 0;
public Vector2 offset = Vector2.zero;
void Start(){
Align((int)alignment, offset);
}
void Align(int i, Vector2 off){
Transform camTransform = Camera.main.transform;
float dist = Vector3.Project((camTransform.position-transform.position), camTransform.forward).magnitude;
Vector3 screenPos = new Vector3(0, 0, dist);
switch(i){
case 0:
screenPos.x = 0 + off.x;
screenPos.y = Screen.height + off.y;
break;
case 1:
screenPos.x = (float)Screen.width/2f + off.x;
screenPos.y = Screen.height + off.y;
break;
case 2:
screenPos.x = Screen.width + off.x;
screenPos.y = Screen.height + off.y;
break;
case 3:
screenPos.x = 0 + off.x;
screenPos.y = (float)Screen.height/2f + off.y;
break;
case 4:
screenPos.x = (float)Screen.width/2f + off.x;
screenPos.y = (float)Screen.height/2f + off.y;
break;
case 5:
screenPos.x = Screen.width + off.x;
screenPos.y = (float)Screen.height/2f + off.y;
break;
case 6:
screenPos.x = 0 + off.x;
screenPos.y = 0 + off.y;
break;
case 7:
screenPos.x = (float)Screen.width/2f + off.x;
screenPos.y = 0 + off.y;
break;
case 8:
screenPos.x = Screen.width + off.x;
screenPos.y = 0 + off.y;
break;
}
transform.position = Camera.main.ScreenToWorldPoint(screenPos);
}
Scribe
Answer by AlucardJay · Apr 15, 2014 at 08:36 PM
ok, so I have seen this question asked a few times, and I needed a solution myself, so have started work on a method to reposition 3D HUD (GUI) items based on screen aspect ratio. I wanted to create a system where you could place items in the Scene view, then store some relative offsets instead of inputting them, to give a wysiwyg solution. Then when the app was run, these objects would reposition themselves at Start to look the same as they did in the editor.
How does it work?
Items are stored in an array, and given a corner of the screen to use as a reference. After the items have been positioned, ContextMenu is used to run a function, that calculates an offset in relation to the camera view fustrum. Then the scene can be saved with these offset values populated. So a Vector3 is calculated based on the perpendicular distance between the item and the camera, which is a projection of each corner of the view fustrum. Then the offset between this Vector3 and the item is stored. The same process happens when the app is run, the reference point is again calculated based on the perpendicular distance and the projected corner of the view fustrum, and the offset is applied to the item position.
How do I use it?
Create an empty gameObject and attach the script.
Drag and drop the camera you'll be using for the HUD into the Inspector.
Change the size of the HUD Items array for the number of items you have.
Open up each element to see where you can drag and drop your item.
Assign an anchor point, eg if you want the item to always be positioned near the top-left of the screen, select UpperLeft in the anchor variable.
When you have finished setting up the scene, and put all the items in the array, and assigned a relative position, it's time to calculate the offsets.
Right-Click on the script component to show a menu (has Reset, Remove Component, Move Up, Move Down, ect ect)
at the bottom of this menu is an option Save Positions, click on that
now look in the inspector. All the offset values for each item have been populated
then SAVE THE SCENE!
if you move any HUD items around, you must click Save Positions again, then save the scene.
To test :
In the Game window, change the aspect ratio, now the items are in the wrong places. Hit play. All the items should reposition themselves to the relative assigned corners. Hit stop, try a couple aspect ratios, hit play, see if the items reposition themselves.
That's about it!
Refer to the image below if some of that explanation is not clear (I'm not good at expressing myself or explaining things well...)
Disclaimer : this is just something I threw together in a couple of hours, so very much in an alpha stage. I can see room for optimization, a better design method, and an editor script instead of using ContextMenu. Basically there is plenty of room for improvement, and I have only done a very small amount of testing. But the current results are promising.
click on images to enlarge
and here's the script :
HUDPositioner.js
//------------------------------//
// HUDPositioner.js //
// Written by Alucard Jay //
// 4/16/2014 //
//------------------------------//
#pragma strict
#if UNITY_EDITOR
@ContextMenu( "Save Positions" )
function SavePositionsFromContextMenu()
{
Debug.Log("Saving Positions from ContextMenu");
SavePositions();
}
#endif
// Variables
// ----------------------------------------------------------------------------
public var hudCamera : Camera;
public var hudItems : HUDItem[];
enum AnchorPoint
{
UpperLeft,
UpperCenter,
UpperRight,
LowerLeft,
LowerCenter,
LowerRight
}
class HUDItem
{
public var hudItem : Transform;
public var anchor : AnchorPoint;
public var offset : Vector3;
}
// Persistant Functions
// ----------------------------------------------------------------------------
function Start()
{
ResetPositions();
}
// Saving
// ----------------------------------------------------------------------------
function SavePositions()
{
// check if HUD camera has been assigned
if ( !hudCamera )
{
Debug.LogError( "NO HUD CAMERA ASSIGNED IN INSPECTOR" );
return;
}
// loop through hudItems array,
// calculate and return offset for each item
for ( var i : int = 0; i < hudItems.Length; i ++ )
{
hudItems[i].offset = CalculateOffset( hudItems[i] );
}
}
function CalculateOffset( item : HUDItem ) : Vector3
{
var offset : Vector3 = Vector3.zero;
var cameraTx : Transform = hudCamera.transform;
var cubeTx : Transform = item.hudItem;
// Get Perpendicular Distance
var dist : float = Vector3.Distance( cubeTx.position, cameraTx.position );
var targetDir : Vector3 = cubeTx.position - cameraTx.position;
var fwd : Vector3 = cameraTx.forward;
var angle : float = Vector3.Angle( targetDir, fwd );
var cosine : float = Mathf.Cos( angle * Mathf.Deg2Rad );
var perpendicularDist : float = cosine * dist;
// Get Offset
var pos : Vector3 = cameraTx.position;
var halfFOV : float = (hudCamera.fieldOfView / 2) * Mathf.Deg2Rad;
var aspect : float = hudCamera.aspect;
var height : float = perpendicularDist * Mathf.Tan(halfFOV);
var width : float = height * aspect;
var anchorPoint : Vector3 = Vector3.zero;
// Switch based on Anchor
switch ( item.anchor )
{
case AnchorPoint.UpperLeft :
anchorPoint = pos - (cameraTx.right * width);
anchorPoint += cameraTx.up * height;
anchorPoint += cameraTx.forward * perpendicularDist;
break;
case AnchorPoint.UpperCenter :
anchorPoint = pos - (cameraTx.right * 0);
anchorPoint += cameraTx.up * height;
anchorPoint += cameraTx.forward * perpendicularDist;
break;
case AnchorPoint.UpperRight :
anchorPoint = pos + (cameraTx.right * width);
anchorPoint += cameraTx.up * height;
anchorPoint += cameraTx.forward * perpendicularDist;
break;
case AnchorPoint.LowerLeft :
anchorPoint = pos - (cameraTx.right * width);
anchorPoint -= cameraTx.up * height;
anchorPoint += cameraTx.forward * perpendicularDist;
break;
case AnchorPoint.LowerCenter :
anchorPoint = pos + (cameraTx.right * 0);
anchorPoint -= cameraTx.up * height;
anchorPoint += cameraTx.forward * perpendicularDist;
break;
case AnchorPoint.LowerRight :
anchorPoint = pos + (cameraTx.right * width);
anchorPoint -= cameraTx.up * height;
anchorPoint += cameraTx.forward * perpendicularDist;
break;
}
// Calculate Offset
offset = cubeTx.position - anchorPoint;
// return result
return offset;
}
// Loading
// ----------------------------------------------------------------------------
function ResetPositions()
{
// check if HUD camera has been assigned
if ( !hudCamera )
{
Debug.LogError( "NO HUD CAMERA ASSIGNED IN INSPECTOR" );
return;
}
// loop through hudItems array,
// reposition based on stored offset
for ( var i : int = 0; i < hudItems.Length; i ++ )
{
RePositionItem( hudItems[i] );
}
}
function RePositionItem( item : HUDItem )
{
var offset : Vector3 = item.offset;
var cameraTx : Transform = hudCamera.transform;
var cubeTx : Transform = item.hudItem;
// Get Perpendicular Distance
var dist : float = Vector3.Distance( cubeTx.position, cameraTx.position );
var targetDir : Vector3 = cubeTx.position - cameraTx.position;
var fwd : Vector3 = cameraTx.forward;
var angle : float = Vector3.Angle( targetDir, fwd );
var cosine : float = Mathf.Cos( angle * Mathf.Deg2Rad );
var perpendicularDist : float = cosine * dist;
// Get Offset
var pos : Vector3 = cameraTx.position;
var halfFOV : float = (hudCamera.fieldOfView / 2) * Mathf.Deg2Rad;
var aspect : float = hudCamera.aspect;
var height : float = perpendicularDist * Mathf.Tan(halfFOV);
var width : float = height * aspect;
var anchorPoint : Vector3 = Vector3.zero;
// Switch based on Anchor
switch ( item.anchor )
{
case AnchorPoint.UpperLeft :
anchorPoint = pos - (cameraTx.right * width);
anchorPoint += cameraTx.up * height;
anchorPoint += cameraTx.forward * perpendicularDist;
break;
case AnchorPoint.UpperCenter :
anchorPoint = pos - (cameraTx.right * 0);
anchorPoint += cameraTx.up * height;
anchorPoint += cameraTx.forward * perpendicularDist;
break;
case AnchorPoint.UpperRight :
anchorPoint = pos + (cameraTx.right * width);
anchorPoint += cameraTx.up * height;
anchorPoint += cameraTx.forward * perpendicularDist;
break;
case AnchorPoint.LowerLeft :
anchorPoint = pos - (cameraTx.right * width);
anchorPoint -= cameraTx.up * height;
anchorPoint += cameraTx.forward * perpendicularDist;
break;
case AnchorPoint.LowerCenter :
anchorPoint = pos + (cameraTx.right * 0);
anchorPoint -= cameraTx.up * height;
anchorPoint += cameraTx.forward * perpendicularDist;
break;
case AnchorPoint.LowerRight :
anchorPoint = pos + (cameraTx.right * width);
anchorPoint -= cameraTx.up * height;
anchorPoint += cameraTx.forward * perpendicularDist;
break;
}
// Calculate Position based on Offset
cubeTx.position = anchorPoint + offset;
}
// ----------------------------------------------------------------------------
If you have any comments, suggestions or feedback, please leave a comment. If it works for you, upvote makes me smile =]
Answer by BH90210 · Apr 11, 2014 at 02:55 PM
Consider scaling your current setup relative to Screen.width
I thought about that but it makes everything a lot stretched in higher resolutions :/
Answer by ForeignGod · Apr 11, 2014 at 04:13 PM
Add these variables which will be used later in the code.
//Write your own width and height here, 1280x1024(5:4) etc
var native_width : float = 1920;
var native_height : float = 1080;
Then add this code on the top of your OnGUI function.
var rx : float = Screen.width / native_width;
var ry : float = Screen.height / native_height;
GUI.matrix = Matrix4x4.TRS (Vector3(0, 0, 0), Quaternion.identity, Vector3 (rx, ry, 1));
if (GUI.Button(new Rect(10,5,160,50), "This is a button", myStyle))
{
//do stuffs
}
What this will do is that it makes your GUI/HUD always fit to your resolution, so it will always be the same size and have the same position according to the res.
Im not sure if this is what youre looking for, but im currently using it in my project and it works like a charm.
How does your code look like? $$anonymous$$aybe i can still help, or are you using objects as your HUD?
Ok i see, so when you are changing the aspect ratio of the screen after the game is built i suppose it is with a option button of some sort. As in the question you stated that you only changed the ratio with the unity editor so i suppose you should experiment with some sort of option menu to help choosing from aspect ratios/resolution etc.
Try making the button or whatever function you have, reposition your quads according to the screen resolution selected.
if screenratio = "16:9" { move objects to the side } if screenratio = "5:4" { move objects closer etc }
Not real code of course but just a "sketch" i suppose
yeah, the problem is that I don't know how to make that code, since I don't know how to get the screen ratio