How can I show GUI.Box at the current Mouse Pos?

I am trying to make a “right-click context menu” like we see in a lot of programs.

I have the basics working, but the GUI.Box is appearing in a strange way on the Y axis.

Here is the basic code:

// This is where I initialize some of the variables used below. 
// menuStyle is a GUIStyle and menuItems is a GUIContent[]
//
this.height = menuStyle.CalcHeight(menuItems[0], 1.0f) * menuItems.Length;
this.width = 150;
this.bounds = new Rect(0, 0, width, height);

Later in the ContextMenu’s Show() method

if(Event.current.button == rightMouseButton) {
			if(Event.current.type == EventType.mouseUp) {
				isRightClicked = true;
				var pos = Input.mousePosition;
				bounds = new Rect(pos.x, pos.y, width, height);
			}
		}   

Here I am just checking for a right-click, and set the bounds of my GUI.Box to the current mouse position’s (x,y).

Than I finally show the box:

// Legacy code. Basically just bounds again.
Rect listRect = new Rect( bounds.x, bounds.y, bounds.width, bounds.height );

// boxStyle is a GUIStyle			
GUI.Box( listRect, "", boxStyle );
int newSelectedItemIndex = GUI.SelectionGrid( listRect, selectedItemIndex, menuItems, 1, menuStyle );

This is based off the ComboBox script from the UnifyWiki.
What happens when I click is, the box is shown on the correct X point as the mouse, but its at a different Y. If I right-click at the top of the screen the menu is at the bottom. If I right-click at the bottom, its at the top. If I click in the middle, its right under the mouse. It seems my Y value is strange, but when I log the bounds.x and bounds.y to the screen, with the current Input.mousePosition.x and Input.mousePosition.y, they match?!? What am I missing here?

See attached images. The red circle indicates where the mouse pointer was when I right-clicked. You can see where the menu appears.
EDIT: The image control to upload images is not working, so here are some links to the screenshots:

Imgur

Imgur

Imgur

1 Answer

1

GUI coordinates and screen coordinates are different. GUI coordinates start in the upper left, screen coordinates in the lower right. Change line 4 of ContextMenu’s Show() to:

var pos = Event.current.mousePosition; 

This will use the mouse position in GUI coordinates.

Thanks, this really helped! I looked up what you mentioned and found the GUIUtility class has some nice helper methods to go back and forth. Also, I implemented your suggested change and it worked! Thanks again!