Search Unity

[Unity 4.3] Get 2D mouse coordinates relative to the scene

Discussion in 'Scripting' started by BenoitFreslon, Nov 29, 2013.

  1. BenoitFreslon

    BenoitFreslon

    Joined:
    Jan 16, 2013
    Posts:
    166
    Hello,

    I'm new in Unity.

    I would like to get the 2D mouse coordinates relative to the scene.

    With this code I get the mouse coordinates relative to the camera: Input.mousePosition
    The origin is in the left bottom corner.

    I would like to set the potition of one sprite to the mouse coordinates :

    gameObject.transform.position = Input.mousePosition;

    But that doesn't work :-/.

    Any ideas ?

    Thanks
     
  2. soulfreebek

    soulfreebek

    Joined:
    Nov 29, 2013
    Posts:
    1
    Have the same problem, Needs charecter move by mouse press tried this transform.Translate(Input.mousePosition * Time.deltaTime); didn't worked :(
     
  3. popc

    popc

    Joined:
    Nov 13, 2013
    Posts:
    12
    Last edited: Nov 29, 2013
  4. quarag

    quarag

    Joined:
    Nov 3, 2013
    Posts:
    16
    Vector3 pz = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    pz.z = 0;
    gameObject.transform.position = pz;
     
  5. BenoitFreslon

    BenoitFreslon

    Joined:
    Jan 16, 2013
    Posts:
    166
    Great!

    Thanks quarag ;)
     
    z3st0, Chmyke and fwalkerstein like this.
  6. Stef_Morojna

    Stef_Morojna

    Joined:
    Apr 15, 2015
    Posts:
    289
    Thanks :)
     
  7. mysweetangel

    mysweetangel

    Joined:
    Nov 19, 2015
    Posts:
    1
    Does anyone know what to do to make a 2d character follow the mouse without clicking anything
     
  8. krsd

    krsd

    Joined:
    Jan 29, 2016
    Posts:
    1
    Thanks bro, helped a lot :D
     
  9. Zenithin

    Zenithin

    Joined:
    Jun 7, 2016
    Posts:
    35
    Thanks a lot this worked :)
     
  10. GuilhermeZikan

    GuilhermeZikan

    Joined:
    Oct 13, 2014
    Posts:
    6
    Use Vector2
     
  11. theDevOfThat

    theDevOfThat

    Joined:
    May 23, 2022
    Posts:
    2
    Go to quarag's reply
     
  12. theDevOfThat

    theDevOfThat

    Joined:
    May 23, 2022
    Posts:
    2
    What does 'pz.z = 0;' mean?
     
  13. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,487
    Please don't necro threads like this. This post is 7 years old.

    I'll move this thread to the scripting forum where it belongs.