Search Unity

Scale GUI based on FOV

Discussion in 'Scripting' started by matthewseaward, Jul 28, 2015.

  1. matthewseaward

    matthewseaward

    Joined:
    Apr 12, 2013
    Posts:
    50
    Hi,

    For my current project I have a health bar and two icons that I want to be drawn under the character. I've been using the code:
    Code (CSharp):
    1. Vector3 loc = mainCamera.GetComponent<Camera>().WorldToScreenPoint(transform.position);

    To draw GUI objects (such as rect and textures) in the 3D space. The issue I now have is that when you zoom in/out (by adjusting the Field Of View) the GUI objects don't scale and take up more/less of the screen than they need to.

    I imagine I need to scale the GUI elements based upon the FOV - or is there a better way to either handle the zoom or the drawing of GUI objects in a 3D space?

    Images showing the fixed image sizes are you zoom in and out.
    2015-07-28 20_33_09-Unity Personal - MainMenu.unity - RPG - PC, Mac & Linux Standalone _DX9_.png 2015-07-28 20_33_20-Unity Personal - MainMenu.unity - RPG - PC, Mac & Linux Standalone _DX9_.png
     
  2. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
    The way I generally do it, is design everything at 1920x1080, then on start, divide the screen.width by 1920, which will give me a ratio, which I multiply the sizes and locations by.

    This mostly works correctly, however the odd iDevice has a height thats taller, which comes out slightly wrong.
     
  3. matthewseaward

    matthewseaward

    Joined:
    Apr 12, 2013
    Posts:
    50
    Thanks for the response.

    I tried the ratio idea. The defauly FOV is at 60 - so I obtained a ratio from that:

    Code (CSharp):
    1. float ratio =  mainCamera.GetComponent<Camera>().fieldOfView /60;
    2.  
    3.     GUI.DrawTexture (new Rect(loc.x, loc.y, 20 * ratio, 20 *  ratio), image);
    But whilst the images are resizing based upon the zoom, it's not constant with the FOV.

    Normal: 2015-07-29 18_05_20-Unity Personal - MainMenu.unity - RPG - PC, Mac & Linux Standalone _DX9_.png
    Shrunk too much: 2015-07-29 18_05_29-Unity Personal - MainMenu.unity - RPG - PC, Mac & Linux Standalone _DX9_.png
     
  4. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
    FOV and screen resolution are two different things so im not sure my solution would work. You need to multiply every value by the FOV though (including X,Y pos).

    Im curious why you are changing the FOV? Is this your method of zooming?
     
  5. matthewseaward

    matthewseaward

    Joined:
    Apr 12, 2013
    Posts:
    50
    Yes, everywhere I look for zooming suggests to adjust the FOV - I'm aware it may not be the best method - just haven't found an alternative at present...
     
  6. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
    I would opt for moving the camera in/out rather than adjusting the fov.