1

I need to obtain display coordinates of the mousePosition by clicking "Fire1" button. The script is very simple, and I get what I need. But I would like the coordinates to be more precise.

public class exmp : MonoBehaviour
 {
     public void Update()
     {
         if(Input.GetButtonDown("Fire1"))
         {
             Debug.Log(Input.mousePosition.x + ", " +Input.mousePosition.y);
         }
     }
 }

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!

ivanshv
  • 47
  • 1
  • 2
  • 7
  • 1
    Input.mousePosition is in pixel coordinates, it should range from (for example) 0 to 1600, not decimal values? – nbura Jul 16 '19 at 15:52
  • @nbura I used to think the same way, but it appears that it's not, can't really explain why. The problem is that Debug.Log rounds the output, and I want to avoid it. – ivanshv Jul 16 '19 at 15:59
  • Possible duplicate of [Get position of an object up to 3 decimal places in unity](https://stackoverflow.com/questions/37162041/get-position-of-an-object-up-to-3-decimal-places-in-unity) – DomCR Jul 16 '19 at 16:06
  • @dom93 I've seen that question. There is a bit different function there, where the code includes Vector3. I tried to use the solution, but without success. – ivanshv Jul 16 '19 at 16:23

1 Answers1

1

Input.mousePosition indeed returns a Vector3 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 for Vector3 and float 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
derHugo
  • 83,094
  • 9
  • 75
  • 115