Checking if a touch position is over a button

Hi All,

I have searched around for an answer to this with no avail… I have seen some suggestions of using raycasts etc but seems like overkill.

Basically I want to test if a touch position is over a GUI button.

I am currently doing it by saying if the touch position x and y are less than button position ± button size x and y etc

This does (sort of) work apart from when changing resolutions (or indeed on different devices).

The problem is the size of the button, the position seems correct from the rect component and that even changes correctly for a given resolution.

I thought I was onto a winner when I thought of using the standard dimensions and scaling the buttons size from the canvas scaler controlled canvas when checking x and y are within that limit but it isn’t working properly…

Any ideas?

Cheers,
Bob

If it’s a touch, and it’s a button, won’t “touch” being over the “button” press the button?

Sorry, I am using the UI not the old GUI

Edited at the same time, lol.

Well, I use the touch so that I can press anywhere on the screen to pick a target position. The problem I am having is that if I press a UI button (say a pause button) the touch is used as well as the button being pressed, so I get a target pos being set and then the pause kick in.

There are several built in methods for this.

1 Like

Oh, that. I solved that by putting the following:

if (UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())
{
    return;
}
1 Like

I tried that method which worked well with the mouse but had problems with touch screens.

I have managed to solve this with my script (I had made a schoolboy error!).

For those interested it is simply:

public bool ButtonContainsPosition( Vector2 xPos )
{

float fMinX = m_xButtonRect.transform.position.x-((m_xButtonRect.sizeDelta.x*0.5f)m_xMenuManager.GetCanvasScaleFactor() );
float fMaxX = m_xButtonRect.transform.position.x+((m_xButtonRect.sizeDelta.x
0.5f)m_xMenuManager.GetCanvasScaleFactor() );
float fMinY = m_xButtonRect.transform.position.y-((m_xButtonRect.sizeDelta.y
0.5f)m_xMenuManager.GetCanvasScaleFactor() );
float fMaxY = m_xButtonRect.transform.position.y+((m_xButtonRect.sizeDelta.y
0.5f)*m_xMenuManager.GetCanvasScaleFactor() );

if( xPos.x <= fMaxX && xPos.x >= fMinX )
{
if( xPos.y <= fMaxY && xPos.y >= fMinY )
{
return true;
}
}

return false;
}

Where the GetCanvasScaleFactor is taken from the canvas scale (I use a canvas scaler).

Works a treat with no raycasting/events or anything like that.

2 Likes

omg, thanks so much, i have been looking for this solution for way toooo long.
For the people who dont want to do any work themselves:
ButtonContainsPosition(touch.position)
var m_xButtonRect = button.GetComponent();
And Public Canvas m_xMenuManager;