Position an object based off of resolution?

Hey,

So I have a bunch of objects, I’ve placed on the screen, and since they are related to the gui, I need them to keep their positions regardless of resolution changes. I’ve done a bit of searching and found some answers but all are vague or still leave me confused.

I’m not the best at math, so I’m not sure how to tackle this. Do I need to first find the screen to pixel coordinates of each object that I’ve set up, and then find it’s percentage of where it is versus Screen.width, and .height?

If someone could walk me through a small example, I’d greatly appreciate it.

Thanks

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.

[25248-hud+positioner+instructions+1.jpg*_|25248]

click on images to enlarge

[25249-hud+positioner+instructions+2.jpg*_|25249]

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 =]
*
*