Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Detecting a mouse shake

Discussion in 'Scripting' started by Tribalbob, Sep 22, 2016.

  1. Tribalbob

    Tribalbob

    Joined:
    Mar 18, 2013
    Posts:
    12
    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.
     
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    8,998
    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()..
     
  3. Tribalbob

    Tribalbob

    Joined:
    Mar 18, 2013
    Posts:
    12
    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?
     
  4. Laperen

    Laperen

    Joined:
    Feb 1, 2016
    Posts:
    1,065
    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.
     
  5. IsGreen

    IsGreen

    Joined:
    Jan 17, 2014
    Posts:
    206
    You can use Mouse X and Mouse Y axis:

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Test : MonoBehaviour {
    5.  
    6.     public bool shake;  
    7.  
    8.     Vector2 oldMouseAxis;
    9.  
    10.     void Update()
    11.     {
    12.         Vector2 mouseAxis = new Vector2(Input.GetAxis("Mouse X"),Input.GetAxis("Mouse Y"));
    13.         this.shake = Mathf.Sign(mouseAxis.x) != Mathf.Sign(this.oldMouseAxis.x) ||
    14.                      Mathf.Sign(mouseAxis.y) != Mathf.Sign(this.oldMouseAxis.y);      
    15.         this.oldMouseAxis = mouseAxis;
    16.         //if (this.shake) Debug.Log(Time.time);
    17.     }
    18.  
    19. }