- Home /
are there some way to determine whether the mouse is moving or not.
are there some way to determine whether the mouse is moving or not.
Answer by Rasmus Schlnsen · Oct 22, 2010 at 08:16 AM
Here is some sample code that works:
private Vector3 tmpMousePosition;
void Start(){ tmpMousePosition = Input.mousePosition;
}
void Update(){
if (tmpMousePosition != Input.mousePosition){ Debug.Log("Mouse moved"); tmpMousePosition = Input.mousePosition }
}
I want to deter$$anonymous$$e whether the mouse is moving or not every frame.
3Q!I have already understanded your code ,thk you very much!!
Answer by zannghast · Oct 22, 2010 at 08:48 AM
Yes there is. Here's a simple way of detecting mouse movement (and direction of movement while you're at it):
Set the appropriate Axes values first
1) Navigate to Edit > Project Settings > Input. You should see the Inspector tab change and display the Axes values.
2) Look for the Axes named "Horizontal" and "Vertical" near the bottom of the list of Axes names (remember, the bottom, not the top)
3) Expand each one and you should see the "Type" property. Change the value on that to "Mouse Movement"
Now you're ready to use code to detect the change
These are really basic stuff. I'm just showing you how you could potentially use it okay?
1) Detecting a change in horizontal mouse movement:
// calculation variables float current_x = 0.0f;
// states bool x_changed = false;
// string references to speed string manipulation/calculation string x_axis = "Horizontal";
//initialize your variables here void Awake() { // initialize your current x with the current change in x axis current_x = Input.GetAxis(x_axis); }
void Update() {
if (DidMove()) {
Debug.Log("Mouse moved horizontally.");
}
}
bool DidMove() { // get the current change in horizontal mouse movement current_x = Input.GetAxis(x_axis);
// check if the current x has a value of 0. if not, return true;
if (current_x == 0)
return false;
else
return true;
}
What happens in the code above is that every Update, the game checks if mouse moved horizontally. This check is done by function DidMove(), which returns a true if the position of the mouse along the x axis changes. This position is further determined by the built-in function Input.GetAxis("Horizontal"), or in this case Input.GetAxis(x_axis) - we simply cached in the string "Horizontal" to avoid any sort of overhead resulting from using string literals.
This built-in function returns a value in the range of -1 to 1, depending on the actual mouse movement.
Note that this code will not work had we forgotten to change the Axes values under Edit > Project Settings > Input.
Here's a link to the scripting reference page for this function: Link
I wasn't able to test the code by the way, but that would be a pretty simple way of detecting change in x. By the way, I highly recommend that you look to the scripting reference page first. You may find your answer there before you post your questions here. ;)