Thursday, December 4, 2014

Unity: Mouse Event Handling

To handle mouse event on a game object, we can write a C# script attached to the game object, in which the MonoBehavior derived class implements the following event handlers:

void OnMouseEnter(): handler triggered when the mouse moves over the game object
void OnMouseExit(): handler triggered when the mouse moves outside the game object
void OnMouseDown(): handler triggered when the mouse button is down on the game object
void OnMouseUp(): handler triggered when the mouse button is up on the game object

The above methods allow the game object to identify when the mouse is over it, or when the mouse is pressed and released over it, and behave accordingly (e.g., by change to highlight color, etc). Remember to apply a Component->Physics->Box Collider on the game object otherwise the above events will not be fired.

There are a set of methods from the Input class which returns a flag indicating whether a mouse button is pressed, for example:

Input.GetMouseButton(0) : return true if the left mouse button is pressed down
Input.GetMouseButton(1) : return true if the right mouse button is pressed down

There are also a set of methods from the Input class which returns the distance moves by the mouse, for example:

float Input.GetAxis("Mouse X") : return distance on screen for a the mouse moves left or right (positive or negative, respectively)
float Input.GetAxis("Mouse Y") : return distance on screen for a the mouse moves upward (positive) or downward (negative)
Vector3 Input.mousePosition: return the screen coordinate of the mouse position
float Input.GetAxis("Mouse ScrollWheel"): return the extent of mouse wheel scrolling


No comments:

Post a Comment