Unity – Detecting Mouse Movement In Specific Directions

I’ve been looking around on the Unity forums and found a few posts about how to detect mouse movement. I’ve seen some interesting and very lengthy code snippets involving creativity and a lot of math just to find out what direction the mouse moved from it’s last known position. My congratulations on people’s problem solving skills and creativity. Those are indeed great qualities to have! Good programmers also do not re-invent the wheel. You can then use that creativity and number crunching brain power to accomplish more in less time. And remember… the Unity documentation is your best friend.

What I’m going to show you has been around since Unity version 5 and is still valid in the latest version of Unity, 2020.3, as of the date of this post.

                if(Input.GetAxis("Mouse X") > 0)
                {
                   //do something when mouse x axis is positive (moving to the right)
                }
                if(Input.GetAxis("Mouse X") < 0)
                {
                    //do something when mouse x axis is negative (moving to the left)
                }

You would put this in your Update() method. It’s also easy to see how to do this with the Y axis now the X axis has been shown in the example above. However, upon reading the Unity documentation regarding this very topic you will learn some important info about the positive and negative direction along the mouse Y and X axes…

Typically a positive value means the mouse is moving right/down and a negative value means the mouse is moving left/up.“(https://docs.unity3d.com/ScriptReference/Input.GetAxis.html)

With this info you can now use a bool data type which can be turned on or off on the UI. You can provide the end user/player the option to invert the Y axis in your game.

Also to help with your debugging skills if your script inherits from MonoBehaviour you can use

print(“debug log stuff here”);

and get the same results as using

Debug.Log(“debug log stuff here”);

I hope you’ve found this useful.

🙂