# Splitting a rect into 4 triangular pieces.

Iโm trying to make a rectangular button that has four sections. They would be split from corner to corner into 4 sections, like an X going through a square. I want to use the OnPointerClick event handler to see which section of the rect the user is clicking on.

I have been trying to math it out for a while and keep scrapping it. Maybe this will come easier to someone else?

Here is what I have at the moment, which works for squares, but not rectangles:

``````public void OnPointerClick(PointerEventData eventData)
{
RectTransform rect = GetComponent<RectTransform>();
Vector2 clickPos = eventData.position;

//Get center to set middle to 0
var centerX = rect.sizeDelta.x / 2;
var centerY = rect.sizeDelta.y / 2;

clickPos.x -= centerX;
clickPos.y -= centerY;

if (clickPos.x > Math.Abs(clickPos.y))
{
Debug.Log("right");
}
else if (clickPos.y > Math.Abs(clickPos.x))
{
Debug.Log("top");
}
else if (-clickPos.x > Math.Abs(clickPos.y))
{
Debug.Log("left");
}
else if (-clickPos.y > Math.Abs(clickPos.x))
{
Debug.Log("bottom");
}

Debug.Log(clickPos);
}
``````
1 Like

Transform the click point to get a relative offset to the center of the button, where all four triangles would meet. If you have a non square button, multiply the new y coordinate with the aspeect ratio of the button. Then simply compare the absolute value of the x and y values of your relative point to find the largest one, this is your direction.
If abs(x) larger than abs(y) you know right or left was pressed, if x is positive then right otherwise left.

1 Like

This is where Iโm having issues. The buttons sizes vary at runtime.

1 Like

It should just be x/y if you modify the y.

2 Likes

While you can use math (and it should not be that difficult - you should get away with an ugle cascace of three โifโ statements per section, you can completely cheat your way out of this by using 4 polygon (one for each triangle) colliders and simply determine which was clicked on.

1 Like

This was it, just need to do it separately if itโs scaled on the X. Thanks man

1 Like