Unity 鼠標點擊事件


鼠標事件

 鼠標事件,都是當鼠標和GUI或者碰撞體(Collider)交互的時候觸發的。

 需要注意的是,drag 其實就是鼠標 Down 后到 Up 之前持續每幀都會發送此消息。

常見的鼠標事件:

  • OnMouseDown:當鼠標上的按鈕被按下時觸發的事件

  • OnMouseDrag:當用戶鼠標拖拽GUI元素或碰撞體時調用

  • OnMouseEnter:當鼠標進入物體范圍時被調用

  • OnMouseExit:當鼠標退出時被調用

  • OnMouseOver:當鼠標移動到某對象的上方時觸發的事件

  • OnMouseUp:當鼠標按鍵被松開時觸發的事件

按下事件:Input.GetMouseButtonDown()

 當鼠標某一個按鍵按下時,便會返回 True,但是即使玩家一直按着鼠標按鍵,也僅僅只會返回一次 True。

 1     void Update()
 2     {
 3         if (Input.GetMouseButtonDown(0))
 4         {
 5             print("鼠標左鍵被按下!");
 6         }
 7         if (Input.GetMouseButtonDown(1))
 8         {
 9             print("鼠標右鍵被按下!");
10         }
11         if (Input.GetMouseButtonDown(2))
12         {
13             print("鼠標中鍵被按下!");
14         }
15         if (Input.GetMouseButtonDown(3))
16         {
17             print("鼠標側鍵被按下!");
18         }
19     }

 這個方法只有一個參數,其中:0 表示鼠標左鍵,1表示鼠標右鍵,2表示鼠標中鍵,3和4分別表示鼠標的兩個側鍵。

 觸發結果:

 

抬起事件:Input.GetMouseButtonUp()

 鼠標在按下后肯定要抬起,按下的時候觸發按下事件,抬起的時候觸發抬起事件。

 1     void Update()
 2     {
 3         if (Input.GetMouseButtonUp(0))
 4         {
 5             print("鼠標左鍵抬起!");
 6         }
 7         if (Input.GetMouseButtonUp(1))
 8         {
 9             print("鼠標右鍵抬起!");
10         }
11         if (Input.GetMouseButtonUp(2))
12         {
13             print("鼠標中鍵抬起!");
14         }
15         if (Input.GetMouseButtonUp(3))
16         {
17             print("鼠標側鍵抬起!");
18         }
19     }

 與按下事件相同,也只有一個參數,其中:0 表示鼠標左鍵,1表示鼠標右鍵,2表示鼠標中鍵,3和4分別表示鼠標的兩個側鍵。

 觸發結果:

 

長按事件:Input.GetMouseButton()

 檢測鼠標按鍵中某個按鍵一直按下的狀態或者是獲得按下的按鍵,如果一直按着鼠標按鍵,便會多次返回 True。

 1     private float timer = 0;
 2 
 3     void Update()
 4     {
 5         if (Input.GetMouseButton(0))
 6         {
 7             timer += Time.deltaTime;
 8         }
 9         else if (Input.GetMouseButtonUp(0) && timer != 0)
10         {
11             print("鼠標左鍵長按" + timer + "秒!");
12             timer = 0;
13         }
14         if (Input.GetMouseButton(1))
15         {
16             timer += Time.deltaTime;
17         }
18         else if (Input.GetMouseButtonUp(1) && timer != 0)
19         {
20             print("鼠標右鍵長按" + timer + "秒!");
21             timer = 0;
22         }
23     }

 和之前的兩個事件一樣,只有一個參數,其中:0 表示鼠標左鍵,1表示鼠標右鍵,2表示鼠標中鍵,3和4分別表示鼠標的兩個側鍵。

 觸發結果:

 

 

 

*** |  以上內容僅為學習參考、學習筆記使用  | ***


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM