Search Unity

Converting Transform x/y of object using mouse co-ords

Discussion in '2D' started by Zace666, Apr 22, 2015.

  1. Zace666

    Zace666

    Joined:
    Jan 28, 2014
    Posts:
    21
    Im trying to create a 1 screen 2D game. I have the zoom in/out working from full screen to close up on the character.
    Now I am trying to work out HOW to get the character to move to a different position on the screen when I click on it.
    I know at some stage i will have to work out pathing, but thats later on.
    I have used the UI to display the mouse x & y coordinates.
    But these coordinates do not seem to link to the transform x/y/(z) Where as my character starts at x 2.27 and y -219 that equates to a mouse x and y of 734. 115.
    Is there a way to work out the point I am click on the background?
     
  2. TomasJ

    TomasJ

    Joined:
    Sep 26, 2010
    Posts:
    256
    Your character is in world space, which is in units. Sprites default to 100 pixels per unit - you can calculate distances based on that.

    Here's some sample code demonstrating how to move your character towards the mouse position:
    Code (csharp):
    1.  
    2. if (Input.GetMouseButton(0))
    3. {
    4.        Vector2 mousePos = Input.mousePosition;
    5.        Vector2 curPos = Camera.main.WorldToScreenPoint(transform.position);
    6.        Vector2 moveDir = mousePos - curPos;
    7.  
    8.        MoveDir(moveDir);
    9. }
    10.  
    11. public void MoveDir(Vector2 dir)
    12. {
    13.      if (dir == Vector2.zero)
    14.        return;
    15.  
    16.      float maxDist = dir.magnitude;
    17.      dir.Normalize();
    18.  
    19.      dir.y *= 0.6f; // slower vertical movement to compensate for projection
    20.  
    21.      dir *= Time.deltaTime * m_Speed;
    22.      if (dir.magnitude > maxDist)
    23.      {
    24.        dir.Normalize();
    25.        dir *= maxDist;
    26.      }
    27.  
    28.      var rb = GetComponent<Rigidbody2D>();
    29.      rb.MovePosition(rb.position + dir);
    30. }
    31.  
     
  3. Zace666

    Zace666

    Joined:
    Jan 28, 2014
    Posts:
    21
    Great thanks.
    Hmmm, now when I apply this code my player disappears - turns out he is now REEEEEALLLY small - in other words something isnt quite right.
    its a 2d game.... Z is still 0
    The mouse point i clicked on was at coords 500,300 and the transform x and y it ended up at were 48.1214, 28.51565
    Any more help appreciated.
     
  4. TomasJ

    TomasJ

    Joined:
    Sep 26, 2010
    Posts:
    256
    What's the transform scale?
     
  5. Zace666

    Zace666

    Joined:
    Jan 28, 2014
    Posts:
    21
    it doesnt change from 1,1,1