Detecting Touches in a Specific Area

What I am trying to do here is to only player Shoot when he touches/taps the screen on a specific range.
I wanted to limit the screen a little by not letting the player have a touch input at the top and at the very bottom of my screen.

I tried using the method of dividing the screen. This obviously I believe wouldn’t work with what I tried. Or I may have just don’t it completely wrong and my Math is garbage.

The Screen resolution is 1280 x 720 and I am trying to remove at the top 50 pixels from being detected and at the bottom 100 pixels.

        foreach (Touch touch in Input.touches)
        {
            if(touch.position.y > Screen.height / 7.2 && touch.position.y < Screen.height / 14.4)
            {
                Debug.Log("Shooting");
                Shoot();
            }
        }

I am trying to stay away from and Rect or GUI stuff just because I am at this time uncomfortable using it.
Also at this point when touch does work, it just gets called every frame. …

Hi @NightmaresDev

Probably easiest way would be to use UI system and just use Screen space canvas (covers the screen) with one transparent RectTransform element, that has button component, or some custom UI event responding component. This it’s just a matter of resizing the RT.

But if you want to stay with Screen coordinates and math - remember that screen coordinates start from the bottom left (0,0). Also think it through if your screen is 800x600, what do you expect to happen, with your calculation:

If screen is 600 pixels tall, it’s Y-axis 0 is at bottom of screen, and y-axis bottom border should be 50 pixels, above what value should the cursor / touch be to be accepted?

Same for top edge - if screen is 600 pixels tall, touch area is less by some defined height, where must the touch be to be accepted?

With this knowledge, you could create a helper method like this. Borders are just floats with border width in each direction, left and right could be just 0.

public float topBorder;
public float bottomBorder;
public float leftBorder;
public float rightBorder;

bool IsInside (Vector3 p)
{
	if (p.x < leftBorder) 
		return false;

	if (p.x > Screen.width - rightBorder) 
		return false;

	if (p.y < bottomBorder) 
		return false;

	if (p.y > Screen.height - topBorder)
		return false;

	return true;
}

> it will detect touch in spacific area

    public RectTransform touchArea; // Assign it recttransform
    Camera cam_Component; // Assign it canvascamera
     
  private void Start()
{
       cam_Component = canvas_Camera.GetComponent<Camera>();
}
    private void update()
{
      if (Input.touchCount > 0)
              {
		         touch = Input.GetTouch(0);
		if (RectTransformUtility.RectangleContainsScreenPoint(touchArea touch.position,cam_Component))
		{
			
			Debug.Log("Detect Touch in spacific area ");

	
	         }
	 
        }
 }