- Home /
use HitTest to check if a screen area is touched
I'm developing a game for Android. I have created various Textures (not GUITextures!) to use as buttons and i've placed them at relative positions on the screen so they can be moved and resized according to screen resolution. Now i need to code this: when the user touches a specific area of the screen (where one of these textures is, but this is not important) something happens. I tried to use HitTest but Unity keeps giving me the error "an istance of type 'UnityEngine.GuiElement' is required to access non static member 'HitTest' ". Is there a way i can use HitTest just to check if an area of the screen has been touched without using GuiTextures?
This is the code i've used (well, it's copied from unity scripting reference)
function Update () {
if(guiText.HitTest(Vector3(100,100,0))){
//something happens
}
}
Answer by aldonaletto · Aug 19, 2012 at 02:57 PM
No, HitTest is GUITexture stuff. Textures drawn with the new GUI system (GUI.DrawTexture) aren't seen by HitTest. You should use GUITexture do display the buttons and be able to use HitTest - this would also allow multitouch capability. Take a look at my answer to this question - I have not tested it (my tablet has broken) but suppose it may be at least a good starting point.
Is there another way to check if the touch is inside a rect?
You can use Rect.Contains:
if (rButton.Contains(touch.position)){
print("button 1 clicked");
}
But keep in $$anonymous$$d that the rectangles passed to the new GUI system have an inverted Y coordinate (0 is the top, Screen.height is the bottom). You can use the same rectangles that define the texture position/size in DrawTexture, but should invert the touch position y coordinate:
var but1: Texture2D; var but2: Texture2D; var r1 = Rect(10,10,200,30); var r2 = Rect(220,10,200,30);
function OnGUI(){ GUI.DrawTexture(r1, but1); GUI.DrawTexture(r2, but2); }
function Update(){ if (Input.touchCount > 0){ for (var touch: Touch in Input.touches){ var pos = touch.position; // invert Y coordinate: pos.y = Screen.height - pos.y; if (r1.Contains(pos)){ print("button 1 pressed"); } else if (r2.Contains(pos)){ print("button 2 pressed"); } } } }