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

Resolved Help with Mathf.Round on player transform position

Discussion in 'Scripting' started by iimuli, Aug 24, 2022.

  1. iimuli

    iimuli

    Joined:
    Apr 21, 2022
    Posts:
    10
    Hey! I'm a complete beginner in scripting. I'm trying to get my player to move to middle of 2D (x,y) square area on mouse click.

    Code (CSharp):
    1.    
    2.  public Vector3 worldPosition;
    3. //...
    4.  void Update()
    5.     {  
    6.         if (Input.GetMouseButtonDown(0))
    7.         {
    8.             MovePlayer();      
    9.         }
    10.     }
    11.  
    12.     void MovePlayer()
    13.     {
    14.         Vector3 mousePos = Input.mousePosition;
    15.         mousePos.x = Mathf.RoundToInt(Input.mousePosition.x);
    16.         mousePos.y = Mathf.RoundToInt(Input.mousePosition.y);
    17.         mousePos.z = Camera.main.nearClipPlane;
    18.         worldPosition = Camera.main.ScreenToWorldPoint(mousePos);
    19.         Debug.Log(worldPosition);
    20.         player.gameObject.transform.position = worldPosition;
    21.     }
    This moves my player directly on my mouse position with float coordinates, not rounding it to int. I tried both Mathf.Round and Mathf.RoundToInt. Is there a simple fix for this code or am I doing it completely wrong?
     
  2. Magiichan

    Magiichan

    Joined:
    Jan 5, 2014
    Posts:
    403
    Input.mousePosition already are intergers, so there's no point in rounding them.
    What's the middle of a 2D square area you're talking about?
    Is it a gameObject or a theoretical grid system you're trying to make work?

    The solution to your problem would be rounding the worldPosition instead of the mousePosition.
    Code (CSharp):
    1. player.gameObject.transform.position = new Vector3(Mathf.Round(worldPosition.x), Mathf.Round(worldPosition.y), worldPosition.z);
     
    iimuli likes this.
  3. iimuli

    iimuli

    Joined:
    Apr 21, 2022
    Posts:
    10
    This worked! Thank you very much!

    What I meant by 2D square area was that ive set all my floor sprites to 0,0 0,1, 1,1 coordinates etc... im not sure about the correct terminology
     
    Magiichan likes this.