Note: There are some syntax errors in the code i wrote as example, this is just pseudo code, I posted my own code from my script under it.
This question may seem long, but its actually fairly short, I just wrote alot of stuff to put you guys in context.
Hi guys, I’m coding a box selection system, and I want to display my box on screen by a GUI.Box.
However, the arguments for Input.mouseposition start from the bottom left of the screen, E.G:
Vector2 MousePos = Input.MousePosition;
If your mouse is at the bottom left of screen it will give:
MousePos = (0,0)
And the Arguments for GUI.Box are:
(Left, Top, Width, Height)
So if you enter your MousePos of (0,0) (bottom left) in there:
GUI.Box(new GUI.Box(MousePos.x (0), MousePos.y (0), 100, 100));
This will start the box from the top left instead of the bottom left, since the origin of the box starts from the top of the screen and the origin of input.mouseposition starts from the bottom of the screen!
Add all of this together, if my MousePos.y is 100, the box will not start 100 units from the bottom of the screen, but 100 units from the top of the screen, mirroring the Y position of the mouse on the horizontal axis of the screen!
My question is: How can I manage to get the “Top” argument from my GUI.Box to match the Input.MousePosition.y on my game screen?
Here is my code:
void Update () {
if(Input.GetButton("Fire1")){
if(LeftMouseDown == false){
LeftMouseDown = true;
mouseOriginalPos = Input.mousePosition;
}
mouseCurrentPos = Input.mousePosition;
SelectionBox = new Rect(Mathf.Min(mouseOriginalPos.x, mouseCurrentPos.x), Mathf.Min(mouseOriginalPos.y, mouseCurrentPos.y),
Mathf.Abs(mouseOriginalPos.x - mouseCurrentPos.x), Mathf.Abs(mouseOriginalPos.y - mouseCurrentPos.y));
}
void OnGUI(){
if(LeftMouseDown == true)
GUI.Box(new Rect(mouseOriginalPos.x, mouseOriginalPos.y, mouseCurrentPos.x - mouseOriginalPos.x, mouseOriginalPos.y - mouseCurrentPos.y), "");
Debug.Log(mouseOriginalPos.y);
}
the SelectionBox Rect variable is in no way affecting my GUI.Box
LeftMouseDown is a bool variable that I reset to false once i release my mouse button.
Notice that I directly enter mouseOriginalPos.y as the “Top” argument of the box, resulting in this “mirror” effect of the mouse position and top of the box.
Thank you very much for anyone who can help!
Thanks for the quick answer, I accepted this as the answer for my question, however, I would like to ask how you go about writing code that does what you just said? Do I get a variable, for example: public vector2 GUIMousePos; and then set it to Event.Current.MousePosition right after my Onbutton("fire1") in update? Scratch that, I tried and it always returns 0 as the y position of the mouse Any Ideas? :)
– RedmothSo if Event.current.type == EventType.mouseDown then you need to do your selection box stuff, in OnGUI, with Event.current.mousePosition
– whydoidoitAhaa, yes, that clears everything up for me, thank you very much!! :)
– Redmoth