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. Dismiss Notice

Using ScreenPointToLocalPointInRectangle outside of BaseEventData

Discussion in 'Immediate Mode GUI (IMGUI)' started by Nihao, Nov 7, 2014.

  1. Nihao

    Nihao

    Joined:
    Oct 22, 2012
    Posts:
    13
    I would like to create an object that follows my mouse cursor in the new UnityGUI.

    As there is no event that would give me a continuous stream of data whenever the pointer hovers over the RectTransform (there is IMoveHandler / OnMove but that doesn't get triggered, not sure what is it for), I need to calculate the position myself.

    I tried:
    Code (CSharp):
    1. RectTransformUtility.ScreenPointToLocalPointInRectangle(GetComponent<RectTransform>(), Input.mousePosition, Camera.main, out localPoint)
    But that doesn't seem to work, so what other approach can I take to get this done? Mind you, I don't have any BaseEventData (PointerEventData etc.) using this approach as this is not part of the event system.
     
  2. Anifacted

    Anifacted

    Joined:
    Dec 1, 2014
    Posts:
    1
    I would really like to know this too.
    If there is any other way of calculating the local point in a RectTransform, independently of the event system.
     
  3. Pallav-Nawani

    Pallav-Nawani

    Joined:
    Jul 28, 2014
    Posts:
    5
    Try passing null instead of Camera.main.
    Worked for me. No idea why it should be so. :rolleyes:
     
    scorpioservo and PastequeBuild like this.
  4. bigSky

    bigSky

    Joined:
    Jan 31, 2011
    Posts:
    114
    Code (CSharp):
    1. Canvas myCanvas = GetComponent<Transform>().root.GetComponent<Canvas>();
    2. Vector2 pos;
    3. RectTransformUtility.ScreenPointToLocalPointInRectangle(myCanvas.transform as RectTransform, Input.mousePosition, myCanvas.worldCamera, out pos);
    4. //if we want to follow the mouse we do this:
    5. transform.position = myCanvas.transform.TransformPoint(pos);
    Take a look at:
    http://answers.unity3d.com/questions/849117/46-ui-image-follow-mouse-position.html