- Home /
Detecting which way my mouse is moving the most
Hello my question is how can i detect which way my mouse is moving the most ? I already have this script -
Vector3 lastMouseCoordinate = Vector3.zero;
void Update()
{
Vector3 mouseDelta = Input.mousePosition - lastMouseCoordinate;
if(mouseDelta.x < 0)
animation.Play(Swing1);
if(mouseDelta.x > 0)
animation.Play(Swing2);
if(mouseDelta.y > 0)
animation.Play(Swing3);
if(mouseDelta.y < 0)
animation.Play(Swing4);
lastMouseCoordinate = Input.mousePosition;
}
This detects if the mouse is moving up,down,left, or right but the problem with this is sometimes when i would move my mouse left it would also detect it moving up or down, i know this is because my mouse is by only a few mm but still how can i detect which direction it is moving in the most.
Thanks
Answer by Benproductions1 · Dec 22, 2013 at 04:43 AM
Hello,
Assuming you only want the directions up, down, left and right, I'll give a few suggestions:
Check which axis has the highest magnitude:
//first we find whether the x or the y axis have a higher magnitude
float xmag = Mathf.Abs(mouseDelta.x);
float ymag = Mathf.Abs(mouseDelta.y);
if (xmag > ymag) {
//mouse is moving mostly along the x axis
if (mouseDelta.x > 0) {
//RIGHT
}
else {
//LEFT
}
}
else if (ymag < xmag) {
//mouse is moving mostly along y axis
if (mouseDelta.y > 0) {
//UP
}
else {
//DOWN
}
}
else {
//NO MOVEMENT
//OR PERFECTLY SIDEWAYS
}
Use the dot product to find which axis the direction of mouseDelta
is closest to:
//will get a 0/0 error if mouse does not move
Vector3 direction = mouseDelta.normalized;
float dot = Vector3.Dot(direction, Vector3.up);
if (dot > 0.5) { //can be >= for sideways
//UP
}
else if (dot < -0.5) { //can be <= for sideways
//DOWN
}
else {
dot = Vector3.Dot(direction, Vector3.right);
if (dot > 0.5) { //can be >= for sideways
//RIGHT
}
else if (dot < -0.5) { //can be <= for sideways
//LEFT
}
}
As you can see, both methods are quite compact, while one handles sideways movement more easily and the other handles no movement more easily. The latter method can also be expanded to support more directions while the upper method is restricted to the number of dimensions.
Hope this helps,
Benproductions1
On your line 16 from the first bit of a code you placed a "<" ins$$anonymous$$d of a ">" Just a small mistake, but for beginners like me it may take them a while to figure out.