[Unity] 偵測滑鼠是否碰觸遊戲畫面邊緣 Detect Mouse on Edge of Screen

2022.05.14 / Unity 引擎

https://www.youtube.com/watch?v=g1m0-TfwI5Q

此腳本是使用傳統 Input Manager 實作,可以取得滑鼠於螢幕邊緣的狀態,可回傳上、下、左、右、上左、上右、下左與下右,如果滑鼠於非邊緣而在畫面中則回傳未知狀態 (Unknown)。

https://www.youtube.com/watch?v=g1m0-TfwI5Q

此腳本是使用傳統 Input Manager 實作,可以取得滑鼠於螢幕邊緣的狀態,可回傳上、下、左、右、上左、上右、下左與下右,如果滑鼠於非邊緣而在畫面中則回傳未知狀態 (Unknown)。

The script was created with legacy Input Manager. It can simply get your mouse state when it is on edge of the screen. The “GetMouseEdgeState” method can return Top, Down, Left, Right, Top Left, Top Right, Down Left, and Down Right state. It also returns an unknown state when the mouse is over the game window.

1public enum MouseEdgeState
2{
3    Unknown,
4    Left, Right, Top, Down,
5    TopLeft, TopRight,
6    DownLeft, DownRight
7}
 1private MouseEdgeState GetMouseEdgeState()
 2{
 3    var mouseX = Mathf.RoundToInt(Input.mousePosition.x);
 4    var mouseY = Mathf.RoundToInt(Input.mousePosition.y);
 5    if (mouseX >= Screen.width)
 6    {
 7        if (mouseY >= Screen.height)
 8        {
 9            return MouseEdgeState.TopRight;
10        }
11        else if (mouseY <= 0)
12        {
13            return MouseEdgeState.DownRight;
14        }
15        else
16        {
17            return MouseEdgeState.Right;
18        }
19    }
20    else if (mouseX <= 0)
21    {
22        if (mouseY >= Screen.height)
23        {
24            return MouseEdgeState.TopLeft;
25        }
26        else if (mouseY <= 0)
27        {
28            return MouseEdgeState.DownLeft;
29        }
30        else
31        {
32            return MouseEdgeState.Left;
33        }
34    }
35    else
36    {
37        if (mouseY >= Screen.height)
38        {
39            return MouseEdgeState.Top;
40        }
41        else if (mouseY <= 0)
42        {
43            return MouseEdgeState.Down;
44        }
45        else
46        {
47            return MouseEdgeState.Unknown;
48        }
49    }
50}

相關文章

Ted Liou

雲科碩士在讀中,專注於 Unity C#、TouchDesigner 技術。
只要願意以超連結標註本文,歡迎轉載或用於教材製作!