Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by Rick74 · Apr 15, 2014 at 02:50 PM · javascriptresolution

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

Comment
Add comment · Show 3
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image robertbu · Apr 15, 2014 at 05:20 PM 0
Share

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.

avatar image AlucardJay · Apr 15, 2014 at 08:37 PM 0
Share

No worries. I have been thinking about this problem myself for a while so am in tune with it. All the Best.

avatar image Rick74 · Apr 15, 2014 at 08:43 PM 0
Share

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!

1 Reply

· Add your reply
  • Sort: 
avatar image
2
Best Answer

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.

alt text

click on images to enlarge

alt text

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


hud positioner instructions 1.jpg (309.7 kB)
hud positioner instructions 2.jpg (143.6 kB)
Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Rick74 · Apr 17, 2014 at 02:20 PM 0
Share

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.

avatar image murkantilism · May 04, 2017 at 04:49 PM 0
Share

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

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

22 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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

Sprites look blurry on larger computer screen. 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges