Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Mouse Screen Position and GUI Position not scaled together.

Discussion in 'Immediate Mode GUI (IMGUI)' started by seansackowitz, May 15, 2013.

  1. seansackowitz

    seansackowitz

    Joined:
    Jul 5, 2012
    Posts:
    1
    I have a matrix to scale the GUI according to the resolution the player selects. I have seen this code in many places, so I assume it works nearly flawlessly. Although, I have not been able to find anyone with a problem similar to mine.

    My code:
    Code (csharp):
    1.  
    2. float originalWidth = 1280;
    3. float originalHeight = 720;
    4. Vector3 scale;
    5.  
    6. void OnGUI()
    7.     {
    8.        
    9.         scale.x = (float)Screen.width / originalWidth; // calculate hor scale
    10.         scale.y = (float)Screen.height / originalHeight; // calculate vert scale
    11.         scale.z = 1;
    12.         Matrix4x4 svMat = GUI.matrix; // save current matrix
    13.         // substitute matrix - only scale is altered from standard
    14.         GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, scale);
    15.         // draw your GUI controls here:
    16.         Vector2 screenPos = Event.current.mousePosition;
    17.         Vector2 convertedGUIPos = GUIUtility.ScreenToGUIPoint(screenPos);
    18.         Debug.Log("Screen: " + screenPos + " GUI: " + convertedGUIPos);
    19.         // restore matrix before returning
    20.         GUI.matrix = svMat; // restore matrix
    21.     }
    22.  
    Code (csharp):
    1. Debug.Log("Screen: " + screenPos + " GUI: " + convertedGUIPos);
    returns the following.

    width: 1153 height: 649
    Screen: (757.1, -56.6) GUI: (840.5, -62.8 )
    Screen: (840.5, -62.8 ) GUI: (933.1, -69.6)

    However, it scales from the top left with both Screen and GUI at 0,0 with the GUI gradually getting out of sync with the Screen.

    The only time when both are scaled correctly is when the screen is 1280 720

    If anyone has any quick solutions, that would be greatly appreciated. Although, I suppose at this point I would take a longer solution as well.

    Edit:
    Added another set of the screen print out as well as the current screen size.
     
    Last edited: May 15, 2013
  2. gamedevelopmenttsunami

    gamedevelopmenttsunami

    Joined:
    Oct 1, 2016
    Posts:
    10
    10 years later, and I have the same problem as well. It seems like the gui.matrix will resize custom mouse cursors but not adjust the mouse.position. So raycasts may not go where you expect.