# Detecting a mouse shake

Been wracking my brain but so far no luck. I need to detect if the user is shaking the mouse - in other words, quick back and forth movements (can be left to right, up/down, etc).

I tried storing the position and checking distance, but a user can just move the mouse around and it still registers, when I need a rough back and forth action. Anyone have any ideas? Doesn’t need to be code examples, just theorycrafting would be good.

Maybe could take direction vector from previous point to current point,
then compare if the next point is going into different direction using angles or dot()…

Yeah, I thought about dot but the problem I ran into is if the mouse moved say, down, and then the user moved it left to right - it never re-registered until they moved it up. I guess maybe reducing the distance check in that case?

Comparing the difference in distance between the last position and current position is the correct way to go.

If you want some general direction, you could compare the difference of a single axis instead of the entire vector

If you want the player to move the mouse at a certain speed you can check for the size of the distance moved.
If you want larger numbers, you can divide the magnitude by time to get velocity instead of just raw magnitude.

You can use Mouse X and Mouse Y axis:

``````using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {

public bool shake;

Vector2 oldMouseAxis;

void Update()
{
Vector2 mouseAxis = new Vector2(Input.GetAxis("Mouse X"),Input.GetAxis("Mouse Y"));
this.shake = Mathf.Sign(mouseAxis.x) != Mathf.Sign(this.oldMouseAxis.x) ||
Mathf.Sign(mouseAxis.y) != Mathf.Sign(this.oldMouseAxis.y);
this.oldMouseAxis = mouseAxis;
//if (this.shake) Debug.Log(Time.time);
}

}
``````