Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity - Check if mouse click was inside of a rect transform

I try to figure out if a mouse click was inside of a rect transform or not.

Each time the user clicked on the screen, a ball will be thrown. But in case the user clicks on the pause button, no ball should be thrown.

I tried to solve with this piece of code but it seems that only the top right quarter of the rect transform is recognized. Here's a short video to show the actual problem: https://youtu.be/gdyDBK6ubgo

Here's the code snippet:

void Update() {
     //Check if user touch on display / click mouse button 
     Vector2 mousePos = new Vector3(Screen.width - Input.mousePosition.x,Screen.height - Input.mousePosition.y, 0); 
     if (Input.GetMouseButtonDown(0) && props.throwable && !checkCollisionWithPauseButton(mousePos) && props.remainingBalls > 0)
     {
         fireBall(Input.mousePosition);
     }
 }

 bool checkCollisionWithPauseButton(Vector3 mousePos){
     //TODO: This does not work very well
     return pauseButton.GetComponent<RectTransform>().rect.Contains (mousePos); 
 }

Here's a screenshot which shows the rect transform.

like image 900
Marvin Krüger Avatar asked Sep 16 '25 03:09

Marvin Krüger


1 Answers

Use RectTransformUtility.RectangleContainsScreenPoint to check if the mouse pointer is in the Rect Transform. This will work regardless of where the rectTransform is positioned locally.

public RectTransform rectTransform;

...

Vector2 mousePos = Input.mousePosition;
RectTransformUtility.RectangleContainsScreenPoint(rectTransform, mousePos);
like image 84
Ruzihm Avatar answered Sep 17 '25 18:09

Ruzihm