- Home /
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
Thanks @alucardj. I missed the question. When he wrote 'relate the gui'. I though he was placing world object with reference to the GUI objects, but it is clear on a reread, that you are right.
No worries. I have been thinking about this problem myself for a while so am in tune with it. All the Best.
sorry robertbu, I was still going though my morning coffee when I asked this.
Alucardj, you should honestly win some sort of award for most detailed answer I have ever see on this website! I thank you sincerely for putting so much time in to help a noob such as myself! (poor robert has been doing most of the heavy lifting up until now)
Let me go through this and see if it does the trick! Thanks again!
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 =]
Hey Alucardj. So I've tried this script and it does exactly as what you described! Thanks again for all the effort you put into answering this question.
Sorry to revive a old thread, @alucardj did you happen to develop this script any further? Into an asset or anything?
Tried searching your username, all I found was slender stuff.
I modified your script to work with an Orthographic camera (basically just disabled any FOV code). It's not perfect but it's much better than nothing! Was hoping to work with you to develop this into an asset, if you haven't already.
Best, Deniz
Your answer

Follow this Question
Related Questions
Setting Scroll View Width GUILayout 1 Answer
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Fixed aspect ratio; window position 1 Answer
How do i create an options menu? 3 Answers