- Home /
Rong position using Rect.Contains and GUI.Button
Hi every one, I started a mini project on Unity 3D and encounter this weird situation, when I use the Contains function and the GUI.Button to get the mouse over a button this happens:
The Rect to use with the Contains function is set using this coordinates and size (0, 0, 128, 64), when I test the function the Rect is on the bottom left and the GUI.Button is on the top left, here is the code.
var rect : Rect = Rect(0, 0, 128, 64);
function OnGUI() { if (rect.Contains(Input.mousePosition)) { print("Its over me"); } else { print("Its out"); }
GUI.Button(rect, "Button");
}
So please any one can explain me why is this difference or it's a kind of bug in the program, also when I use the GUI.matrix = Matrix4x4.TRS() to scale the GUI about the screen size, the GUI.Button conserve the position but the rect move away from the button, for your attention thank you very much.
Then what would the correct variable be for mobile touches? Since Input.touches[0].position; is having the same problem.
Answer by Eric5h5 · Jan 20, 2011 at 04:02 AM
Input.mousePosition uses screen space coordinates, which are inverted from GUI coordinates. Don't use anything from Input in OnGUI, use Event.current instead, like Event.current.mousePosition. Then you get data appropriate for OnGUI.
Thanks for you reply, but my question is about the Rect struct, why if I use the same Rect var to draw a GUI.Button this have another position on the screen when drag the game float window to have a different size (the button keep his position but the Rect dont).
I already answered that. "Input.mousePosition uses screen space coordinates, which are inverted from GUI coordinates."
Eric5h5, you are right, my mistake, it's just I don't really understand that before like I said before I'm new on the unity stuff, once again thanks to your reply, that helps me a lot.
What about do something only if you drag over the area? I try to deter$$anonymous$$e if there is a drag in that area. I wrote this code, but i never get "it is draging!",just the opposite. It works for other events,like click,but I want for drag. Any ideas?, Eric5h5 :D ?
if(swip_area.Contains(Event.current.mousePosition)) if(Event.current.type == EventType.$$anonymous$$ouseDrag) { print("It is draging"); } else{ print("It is not draging!"); }
Found! Just invert: if(Event.current.type == EventType.$$anonymous$$ouseDrag){ if(swip_area.Contains(Event.current.mousePosition)) .....//code//.... }
Your answer
