Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unity jagged mouse input detection

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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();
        }

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading