Is it possible to have more precise Input.mousePosition?
Hi guys,
I need to obtain display coordinates of the mousePosition b clicking "Fire1" button. The script is very simple, and I get what I need. But I would like the coordinates to be more precise.
Currently I'm getting smth like "x, y" or "x.5, y.0", but it is important for the project to get something like "x.abcd, y.efgh". In some examples I've seen that this is quite possible, but I can't figure out how.
Thanks in advance!
using UnityEngine;
using System.Collections;
public class exmp : MonoBehaviour
{
public void Update()
{
if(Input.GetButtonDown("Fire1"))
{
Debug.Log(Input.mousePosition.x + ", " +Input.mousePosition.y);
}
}
}
Answer by ivanshv · Jul 16, 2019 at 05:41 PM
Credits to derHugo from StackOverflow for the answer to my question. Hope it will be helpful to others.
Input.mousePosition
indeed returns aVector3
with float values, though it is in pixel-coordinates but also returns inbetween pixel positions.Anyway actually only the string printing to the console is affected by the lower precision because Unity uses a custom
ToString()
implementation forVector3
andfloat
which is supposed to be better readable.If you use those values for any calculation it uses the pure float values with an even higher precision of ~6-9 digits.
For the printing checkout Standard Numeric Format Strings and Custom Numeric format Strings
You can e.g. use
Debug.Log(Input.mousePosition.x.ToString("0.0000") + ", " + Input.mousePosition.y.ToString("0.0000"));
or using
"Fn"
Debug.Log(Input.mousePosition.x.ToString("F4") + ", " + Input.mousePosition.y.ToString("F4"));
in order to show a
float
value with a precision of **always* 4 decimals.You can instead also use
#
for optional precision so it is cut off if the precision is not required e.g. for
Debug.Log(1.23001f.ToString("0.00##"));
Debug.Log(1.2301f.ToString("0.00##"));
the output will be
1.23
1.2301