Home > Software design >  Detecting cursor in a certain range
Detecting cursor in a certain range

Time:05-05

I'm trying to figure out a way to detect where the cursor is in a certain range. This would be the sort of thing I'm looking for:

if ('bla bla bla' && Input.mousePosition == (in between x1 and x2, in between y1. and y2))

Is this possible in unity, because I can't figure it out :( Thanks for any help!

CodePudding user response:

Vector2 mousePos = Input.mousePosition;

This returns a Vector2 with the coordinates x and y of the mouse position. To check if this point with the coordinates mousePos.x and mousePos.y lies in the range x1 and x2; y1 and y2, we can write

if((mousePos.x >= x1 && mousePos.x <= x2) &&
   (mousePos.y >= y1 && mousePos.y <= y2))
{
    // do something
}

Alternatively,

if(mousePos >= new Vector2(x1, y1) &&
   mousePos <= new Vector2(x2, y2))
{
    // do something
}

CodePudding user response:

also you can use Rect.Contains for Prevent dublication:

var InRect = new Rect(0, 0, Screen.width/2, Screen.height).Contains(Input.mousePosition);

UnityEngine.Debug.Log(InRect);
  • Related