Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

How do I detect when the mouse is outside a specific area of the screen?

Discussion in 'Scripting' started by RayDawg, Oct 9, 2017.

  1. RayDawg

    RayDawg

    Joined:
    Mar 19, 2013
    Posts:
    108
    Let's say I have an invisible 2D circle at the center of the screen and has a radius of 200 pixels. When the mouse is inside this circle, nothing happens, but when the mouse is outside this circle, I want an object to, for example, look at where the mouse's position translated to world space. How would I go about doing that? Can anyone point me in the right direction? Are there any particular resources I could refer to?
     
  2. MathiasDG

    MathiasDG

    Joined:
    Jul 1, 2014
    Posts:
    114
    Code (csharp):
    1.  
    2. if (Vector2.Distance(input.mousePosition, center) < radius) {
    3.     // Mouse is inside the circle with the center and radius.
    4. }
    5. else {
    6.     // Mouse is outside the circle area
    7. }
    8.  
     
  3. RayDawg

    RayDawg

    Joined:
    Mar 19, 2013
    Posts:
    108
    I can't believe I forgot about .Distance(), thanks!
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Another option (just for the record here) is to use the IPointerEnter/Exit handlers.