Detect if mouse is dragged or clicked

I am using raycast on an object and the ray hits when mouse is clicked on the object. However, I do not want the ray to fire if the mouse is being dragged (mouse button being pressed for more than 2 seconds). How do I achieve this?

void Update () {
        RaycastHit hitInfo = new RaycastHit ();
        Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
        if (Input.GetMouseButton (0) || Input.touchCount == 1) {
            if (Physics.Raycast (ray, out hitInfo, 10)) {
                Debug.Log(hitInfo.collider.gameObject.name);
            }
        }
    }

You need to have a timer on-click check if the mouse is being held for 2 seconds, and have it do one thing if it does, and another if it doesn’t.

1 Like

You need to have a little state machine that goes through states like this:

OFF
UNDECIDED
DRAGGED

On any release (and initially) it starts in OFF

On click Down() it goes to UNDECIDED

If more than 2 seconds time pass, it goes to DRAGGED

On click Up() if checks if it is in DRAGGED or not:

  • if in DRAGGED don’t fire the ray
  • if in UNDECIDED, fire the ray

Usually when I implement this I don’t use time but rather distance dragged, for instance if you drag the mouse (or finger) more than 5% of the smallest screen dimension:

float minDimension = Mathf.Min( Screen.width, Screen.height);

float minDistance = 0.05f * minDimension;

if (mouseMovedDistance >= minDistance)
{
   mode = DRAGGED;
}