Unity jagged mouse input detection

Viewed 118

I wrote a script that writes Input.mousePosition into a file on every frame. The idea is that I want to identify which button on screen the player is trying to click before actually clicking, from the speed of the mouse basically. However, I ran into data like this:

(1113.0, 835.0, 0.0)
(1113.0, 835.0, 0.0)
(1113.0, 835.0, 0.0)
(1126.0, 835.0, 0.0)

Basically on one frame the x position is one value, a couple of frames later it's changed, but in the middle there is no gradation. While my mouse movement was continuous, if I'm to believe Unity, in the example above I hovered on 1 pixel for 3 frames then jumped 13 pixels to the right in one frame. Why is this? Is there any code to get the actual frame by frame position of the mouse?

EDIT:

    Vector2 _lastPosition;
    StreamWriter _mouseData;

    // Start is called before the first frame update
    void Start()
        {
        _mouseData = new StreamWriter(File.Open("sdata.txt", FileMode.Create));
        }

    // Update is called once per frame
    void FixedUpdate()
        {
        _mouseData.WriteLine(Input.mousePosition.ToString());
        
        if (Input.GetMouseButtonDown(0))
            {
            _mouseData.WriteLine("CLICK\n\n");
            }

        _lastPosition = Input.mousePosition;
        }

    void OnDestroy()
        {
        _mouseData.Close();
        }

EDIT 2: I changed the code to the following:

void FixedUpdate()
        {           
        _mouseData.WriteLine(Vector2.SqrMagnitude(new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y"))));

        if (Input.GetMouseButtonDown(0))
            {
            _mouseData.WriteLine("CLICK\n\n");
            }
        }

Now I'm still getting output that's 50% 0-es and non-0 values are sprinkled in on every second row. Exceptions: a few rows where actual values are supposed to be still contain random 0-es. Now, I'm not super concerned about getting less frequent than 1/frame data, but there's no way to distinguish between these false 0-es and actual 0-es when the mouse is not moving, which is an issue.

1 Answers

I cannot find out from your question but I am guessing that you use the FixedUpdate() method which is unreliable in this situation. Update() is advised to use for calls that you want to execute once per frame.

EDIT: Also, note that it is recommended that you set your application's framerate to a realistic number since it is unlimited by default (on desktop) and your app could be running with so many FPS that it is faster than how often you can sample your mouse input.

You can set the framerate using: Application.targetFrameRate = 60;

Aside from this problem it is generally a good idea to set your framerate to save yourself some headaches. (This is specifically true if you develop for mobile platforms and test on your desktop.)

Related