Search Unity

Mouse Position for Screen Space - Camera?

Discussion in 'Unity UI (uGUI) & TextMesh Pro' started by shivansps, Jan 30, 2015.

  1. shivansps

    shivansps

    Joined:
    Feb 26, 2014
    Posts:
    58
    Lets say i want a UI.Image to follow the mouse, in a "Screen Space - Overlay" canvas i can do it as easy as

    Image.transform=Input.mousePosition;

    in a LateUpdate.

    But how to do the exact same thing for a Screen Space - Camera canvas?
     
  2. SimonDarksideJ

    SimonDarksideJ

    Joined:
    Jul 3, 2012
    Posts:
    1,625
    Exactly the same, both of the Screen Space canvases cover the entire screen. You might however have to transform the mouse coordinates from world space (through the camera of the Screen Space - Camera canvas) to get the 2D position.
    e.g.

    Code (CSharp):
    1. var screenPoint = Vector3(Input.mousePosition);
    2. screenPoint.z = 10.0f; //distance of the plane from the camera
    3. transform.position = Camera.main.ScreenToWorldPoint(screenPoint);
     
  3. shivansps

    shivansps

    Joined:
    Feb 26, 2014
    Posts:
    58
    Thank you.
     
    SimonDarksideJ likes this.
  4. fmathews34

    fmathews34

    Joined:
    Apr 6, 2016
    Posts:
    1
    this really helped me out, thanks.
     
  5. Vinnie420

    Vinnie420

    Joined:
    Mar 16, 2014
    Posts:
    2
    thanks, this really should be in the documentation
     
  6. SimonDarksideJ

    SimonDarksideJ

    Joined:
    Jul 3, 2012
    Posts:
    1,625
  7. jonathanskidmore1

    jonathanskidmore1

    Joined:
    May 31, 2019
    Posts:
    1
    I know this post is several years old now, but I want to thank @SimonDarksideJ for his answer, I have spent several days wondering why my mouse position seemed to be offset from where it should be I have looked through tons of forums and finally I have found a useful answer. This has given me a much better understanding of how Unity's UI systems work, I cannot thank you enough!
     
  8. naagi

    naagi

    Joined:
    Nov 27, 2014
    Posts:
    6
    this post may be old, but i really thank you for the post, you really save me, thank you so much
     
  9. maxlukonin

    maxlukonin

    Joined:
    Jul 20, 2019
    Posts:
    1
    Dude seven years later you still helped me out on that, really appreciate it :)
     
  10. gamedevbud

    gamedevbud

    Joined:
    Jul 13, 2019
    Posts:
    1
    This is great! Thank you!