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.

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

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.

![alt text][1]

click on images to enlarge

![alt text][2]

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_.offset = CalculateOffset( hudItems *);*_

* }*
}

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 );
* }*_

}

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 =]
[1]: /storage/temp/25248-hud+positioner+instructions+1.jpg
[2]: /storage/temp/25249-hud+positioner+instructions+2.jpg

Consider scaling your current setup relative to Screen.width

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.