Help with Mathf.Round on player transform position

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.

 public Vector3 worldPosition;
//...
 void Update()
    {   
        if (Input.GetMouseButtonDown(0))
        {
            MovePlayer();      
        }
    }

    void MovePlayer()
    {
        Vector3 mousePos = Input.mousePosition;
        mousePos.x = Mathf.RoundToInt(Input.mousePosition.x);
        mousePos.y = Mathf.RoundToInt(Input.mousePosition.y);
        mousePos.z = Camera.main.nearClipPlane;
        worldPosition = Camera.main.ScreenToWorldPoint(mousePos);
        Debug.Log(worldPosition);
        player.gameObject.transform.position = worldPosition;
    }

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?

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.

player.gameObject.transform.position = new Vector3(Mathf.Round(worldPosition.x), Mathf.Round(worldPosition.y), worldPosition.z);
1 Like

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

1 Like