OnMouseDrag Fix in Unity3D

No replies
uke
User offline. Last seen 17 小时 48 分钟 ago. Offline
超级管理员
Joined: 09/07/2009
Points: 2478

OnMouseDrag detects if the mouse is dragging the collider of a GameObject.  However, it is triggered even when the mouse is not moving; it is triggered as soon as the mouse is down.  

An OnMouseMove function would be nice to make this possible, but the only functions provided by MonoBehaviour are the following:

OnMouseDown
OnMouseDrag
OnMouseEnter
OnMouseExit
OnMouseOver
OnMouseUp

But, no OnMouseMove!

Instead, determine mouse movement by checking if its position has changed:

private Vector3 lastMousePos;

private bool isDragging = false;
 

void OnMouseDrag()
{

if( lastMousePos != Input.mousePosition )
isDragging = true

if( isDragging )
print( "dragging!" );

lastMousePos = Input.mousePosition;

}

void OnMouseUp()
{

isDragging = false;

}