How to get exact hit point on a ui object in relation to that objects size

Hello. I have read all over. I have been working with the following code to get on of my ui images to move back and forth with the click and drag of my mouse. It works so far, the problem in that when I click on the ui image, there is an offset position because when I click on the image , i click a different place every time to drag it.

public void OnDrag(PointerEventData eventData)
{

Vector2 positionMid = eventData.position;

float changeInPositionX = positionMid.x - lastPos.x;
float changeInPositionY = positionMid.y - lastPos.y;

img.transform.position = new Vector3(img.transform.position.x, img.transform.position.y + changeInPositionY, 0);

lastPos = positionMid;

}

This code works. What I really need to know is when I click down on a ui object, I want to know the exact position in relation to that object that I clicked. Like say my ui object that I clicked has a width of 200 and height of 200, if I click within thoughs bounds I want to return the hit coordinates within a 200 x 200 range.

I also looked into ray casting and got 2dray casting working with my ui and added a collider to my ui. But I still cannot get these coordinates.

Can anyone help thanks, I am stumped!

I haven’t tested this code but I believe this is what you need:

public void OnDrag(PointerEventData eventData)
{
   Vector2 localCursor;
         if (!RectTransformUtility.ScreenPointToLocalPointInRectangle(GetComponent<RectTransform>(), eventData.position, eventData.pressEventCamera, out localCursor))
           Debug.Log("Did not click inside the IMage");
       else
           Debug.Log("Local Position is : " + localCursor);

This code is assuming this OnDrag is in a script attached to the Object your trying to the local position of. If not you’ll need to change GetComponent Call to be gameObject.GetComponent where gameObject is the gameobject that has your UI object.

1 Like

Wow, that worked. I’m surprised how lost I was. Doing anything ui related is always difficult in game engines. Thanks for the help.

No problem, glad it worked. A Lot of Unity is just knowing the API over any particular programming skill set. There is a lot of useful functions that just take time to learn and get exposed to.