• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
5
Question by Abdul Mueed · Feb 03, 2015 at 11:50 AM · mouseclick

Find x,y cordinates of click on UI.Image new gui system

I want to find where mouse has clicked on ui.image, i have canvas, then there is panel inside a canvas, some percent of canvas is covered with menu where person can select color remaining has an image with black outlines, its flood fill app, i have done everything but stuck at one point.

i want to find where user clicked on image so that i can give that point to my flood fill algorithm, i have tried lot of things, i am now lost if someone can help me, i want position relative to image i can get screen point using Input.mousePosition

PointerEventData eventData = new PointerEventData(EventSystem.current); eventData.position = Input.mousePosition;

         Debug.Log(eventData.pressPosition.x+" - "+eventData.pressPosition.y);

         List<RaycastResult> rayresult = new List<RaycastResult>();
         EventSystem.current.RaycastAll(eventData,rayresult);

         if (rayresult.Count > 1) {
             int len = rayresult.Count;
             for (int index = 0; index < len; index++) {
                 if (rayresult[index].gameObject.tag == "image")
                 {
                  //   Debug.Log("Pos: " + rayresult[index].gameObject.tag);
                     Debug.Log("Pos: " + rayresult[index].gameObject.GetComponent<RawImage>().collider.p);
                 }
             }
         }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

4 Replies

· Add your reply
  • Sort: 
avatar image
24
Best Answer

Answer by Warcel · Apr 20, 2015 at 06:56 PM

I thing this is a beter aproach:

 void DebugPoint(PointerEventData ped)
     {
         Vector2 localCursor;
         if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(GetComponent<RectTransform>(), ped.position, ped.pressEventCamera, out localCursor))
             return;
 
         Debug.Log("LocalCursor:" + localCursor);
     }

You get the local Vector2 on the entire RectTransfom. In my case i need to get the pixel of an image that is atched to a ScrollRect... Of course you will need some math with the pivots, but its a lot easyer...

Comment
Add comment · Show 10 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Fattie · Jun 16, 2015 at 02:58 AM 2
Share

how beautiful

avatar image TechSupportIncoming1 · Jul 06, 2015 at 07:45 AM 0
Share

@Warcel what did ya mean with "math with pivots"?

If I click on the upper left corner, I get a negative values representing half of the width as X and half of the height as Y.

If I click in center I get 0,0

How could I resolve this? I want to have accurate coordinates. Appreciate your help.

avatar image Lev-Lukomskyi TechSupportIncoming1 · Apr 11, 2016 at 10:07 PM 0
Share

You can just set Pivot point to (0, 0) ins$$anonymous$$d of (0.5, 0.5) in inspector settings – and then you could use x = $$anonymous$$athf.FloorToInt(localCursor.x); y = $$anonymous$$athf.FloorToInt(localCursor.y); to get pixel coordinate

avatar image TechSupportIncoming1 · Jul 06, 2015 at 08:32 AM 3
Share

Yes! got it to work! $$anonymous$$y pivots are both 0.5

 void my$$anonymous$$ouseDown(PointerEventData dat)
 {
     Vector2 localCursor;
     var rect1 = GetComponent<RectTransform>();
     var pos1 = dat.position;
     if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(rect1, pos1,
         null, out localCursor))
         return;
 
     int xpos = (int)(localCursor.x);
     int ypos = (int)(localCursor.y);
 
     if (xpos < 0) xpos = xpos + (int)rect1.rect.width / 2;
     else xpos += (int)rect1.rect.width / 2;
 
     if (ypos > 0) ypos = ypos + (int)rect1.rect.height / 2;
     else ypos += (int)rect1.rect.height / 2;
 
     Debug.Log("Correct Cursor Pos: " + xpos + " " + ypos)
 }
avatar image Warcel · Jul 06, 2015 at 12:39 PM 0
Share

exactly like you did :)

avatar image GameDevBryant · May 23, 2016 at 08:50 PM 0
Share

Thanks so much for posting this, taking the RectTransformUtility.ScreenPointToLocalPointInRectangle function allowed me to crack an issue that I have been trying to get my head around for about a week and a half now! Similar situation to OP. Thanks again, you saved the day.

Show more comments
avatar image
2

Answer by Brit1974 · Jan 16, 2018 at 03:23 PM

I'm posting this because the existing solutions are incomplete, and I needed a better solution. They don't account for different situations, like if the pivot values are set. This function will give you back an x,y value where the 0.0,0.0 position is the lower-left corner of the image, and the 1.0,1.0 position is the upper-right corner of the image. Values outside this range are outside the image.

If you want the exact pixel location, you can multiply the values by the size of the sprite. For example, multiply the ptLocationRelativeToImage01.x by uiImageObject.sprite.rect.width, and multiply ptLocationRelativeToImage01.y by uiImageObject.sprite.rect.height.

 // Take an image and a screenPosition. Return the ptLocationRelativeToImage01 relative to the image (where x,y between 0.0 and 1.0 are on the image, values below 0.0 or above 1.0 are outside the image).
 public static bool GetPositionOnImage01 (
     UnityEngine.UI.Image uiImageObject,
     Vector2 screenPosition,
     out Vector2 ptLocationRelativeToImage01 )
 {
     ptLocationRelativeToImage01 = new Vector2();
     RectTransform uiImageObjectRect = uiImageObject.GetComponent<RectTransform> ();

     Vector2 localCursor = new Vector2();
     if (RectTransformUtility.ScreenPointToLocalPointInRectangle (
         uiImageObjectRect,
         screenPosition,
         null,
         out localCursor))
     {
         Vector2 ptPivotCancelledLocation = new Vector2( localCursor.x - uiImageObjectRect.rect.x, localCursor.y - uiImageObjectRect.rect.y );
         Vector2 ptLocationRelativeToImageInScreenCoordinates = new Vector2();

         // How do we get the location of the image? Calculate the size of the image, then use the pivot information.
         if( uiImageObject.preserveAspect )
         {
             // If we are preserving the aspect ratio of the image, then we need to do some additional calculations
             // Figure out if the image constrained by height or by width.
             float fImageAspectRatio = uiImageObject.sprite.rect.height / uiImageObject.sprite.rect.width;
             float fRectAspectRatio = uiImageObjectRect.rect.height / uiImageObjectRect.rect.width;

             Rect imageRectInLocalScreenCoordinates = new Rect();
             if( fImageAspectRatio > fRectAspectRatio )
             {
                 // The image is constrained by its height.
                 float fImageWidth = (fRectAspectRatio/fImageAspectRatio) * uiImageObjectRect.rect.width;
                 float fExcessWidth = uiImageObjectRect.rect.width - fImageWidth;
                 imageRectInLocalScreenCoordinates.Set( uiImageObjectRect.pivot.x*fExcessWidth,0, uiImageObjectRect.rect.height/fImageAspectRatio, uiImageObjectRect.rect.height);
             }
             else
             {
                 // The image is constrained by its width.
                 float fImageHeight = (fImageAspectRatio/fRectAspectRatio) * uiImageObjectRect.rect.height;
                 float fExcessHeight = uiImageObjectRect.rect.height - fImageHeight;
                 imageRectInLocalScreenCoordinates.Set( 0,uiImageObjectRect.pivot.y*fExcessHeight, uiImageObjectRect.rect.width, fImageAspectRatio*uiImageObjectRect.rect.width );
             }
             ptLocationRelativeToImageInScreenCoordinates.Set( ptPivotCancelledLocation.x - imageRectInLocalScreenCoordinates.x, ptPivotCancelledLocation.y - imageRectInLocalScreenCoordinates.y );
             ptLocationRelativeToImage01.Set( ptLocationRelativeToImageInScreenCoordinates.x / imageRectInLocalScreenCoordinates.width, ptLocationRelativeToImageInScreenCoordinates.y / imageRectInLocalScreenCoordinates.height );
         }
         else
         {
             ptLocationRelativeToImageInScreenCoordinates.Set( ptPivotCancelledLocation.x, ptPivotCancelledLocation.y );
             ptLocationRelativeToImage01.Set( ptLocationRelativeToImageInScreenCoordinates.x / uiImageObjectRect.rect.width, ptLocationRelativeToImageInScreenCoordinates.y / uiImageObjectRect.rect.height );
         }
         return true;
     }
     return false;
 }
Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image EL-soNK · May 21, 2019 at 09:17 AM 0
Share

Thanks so much!! This is EXACTLY what I needed, and I could not figure it out myself to get the position after zoo$$anonymous$$g/scrolling in the scroll rect.

avatar image dhami-nitin · Aug 26, 2020 at 01:34 AM 0
Share

Thanks a ton for this!

avatar image
1

Answer by coolraiman · Apr 12, 2016 at 12:36 PM

its that simple. this is what i use and it work like a charm.

in this example i can calculate on wich square of a bingo card the player clicked. This allowed me to avoid having 25 button script per bingo card:

 using UnityEngine;
 using System.Collections;
 using UnityEngine.UI;
 using UnityEngine.EventSystems;
 
 public class CardHitZone : MonoBehaviour , IPointerClickHandler 
 {
 
     int nCard = 0;
 
     // Use this for initialization
     void Start ()
     {
         string numb = transform.parent.name [transform.parent.name.Length - 1].ToString();
 
         if (!int.TryParse (numb, out nCard)) 
         {
 
             Debug.Log ("error, invalid card name");
         } 
         else 
         {
             nCard--;
         }
     }
 
     public void OnPointerClick(PointerEventData ED)
     {
         Vector3 localHit = transform.InverseTransformPoint(ED.pressPosition);
 
 
         int x = ((int)((localHit.x + 62.5f)/25f));
 
         int y = 4 - (int)((localHit.y + 58.5f) / 23.4);
 
         if (x < 0 || x > 4 || y < 0 || y > 4) 
         {
             //out of bound
             return;
         }
 
         GameObject.Find ("Main").GetComponent<GameUpdate> ().wildDab (nCard, x + y * 5);
 
     }
 
 }


with transform.InverseTransformPoint(ED.pressPosition); you get the local position of the click. it is affected by the width and heigth of the sprite in the canvas, if you change the width or height it wil affect the number of pixel in it.

Sprite outside of canvas are different. if the original texture is 512x512, its local coordinate will always be 0 to 512 in x and y even if you change the import setting to 256x256.

for both canvas image and regular sprite you can change the scale without affecting the number of pixel in the local position.

The difference in how to raycast sprite and canvas image and getting their local click position can be puzzling sometimes

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image benzsuankularb · Apr 18, 2018 at 05:07 PM 0
Share

Is it performance reason to have 1 button ins$$anonymous$$d of 25?

avatar image
0

Answer by Mmmpies · Feb 03, 2015 at 01:59 PM

Well the mouse point is that location on the canvas. I just tested it with this:

 using UnityEngine;
 using UnityEngine.UI;
 using UnityEngine.EventSystems;
 using System.Collections;
 
 public class DotClick : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {
 
     private Vector3 clickMousePos;
     private Vector3 clickPos;
     private bool mouseDown;
     public GameObject itemPrefab;
     public Transform ParentPanel;
 
     public void OnPointerDown(PointerEventData ped) 
     {
         mouseDown = true;
         clickPos = transform.position;
         clickMousePos = Input.mousePosition;
         Debug.Log ("clickPos = " + clickPos + "   clickMousePos = " + clickMousePos);
     }
 
     public void OnPointerUp(PointerEventData ped) 
     {
         mouseDown = false;
         GameObject newItem = Instantiate(itemPrefab) as GameObject;
         newItem.transform.SetParent(ParentPanel, false);
         newItem.transform.localScale = new Vector3(1,1,1);
         newItem.transform.position = new Vector3(clickMousePos.x, clickMousePos.y, 0);
     }
 }

I then put a canvas on the empty scene with a full canvas sized panel and dragged that script onto the panel. Then I created a 1 pixel by 1 pixel panel prefab and used that to instantiate where the mouse button goes down. If you want to recreate just drag the panel onto the ParentPanel and an object to instantiate on the itemPrefab. I left them both public for testing.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

16 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

save and move to mouse click positions 1 Answer

Click Point From Raycasting Not Yielding Expected Coordinates 1 Answer

mouse enter Click problem 0 Answers

Detect Mouse Click in a GUITexture 1 Answer

(Mobile) Touch anywhere on screen EXCEPT button 3 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges