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

2022.05.14 / Unity 引擎
https://www.youtube.com/watch?v=g1m0-TfwI5Q 此腳本是使用傳統 Input Manager 實作,可以取得滑鼠於螢幕邊緣的狀態,可回傳上、下、左、右、上左、上右、下左與下右,如果滑鼠於非邊緣而在畫面中則回傳未知

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.

public enum MouseEdgeState
{
    Unknown,
    Left, Right, Top, Down,
    TopLeft, TopRight,
    DownLeft, DownRight
}
private MouseEdgeState GetMouseEdgeState()
{
    var mouseX = Mathf.RoundToInt(Input.mousePosition.x);
    var mouseY = Mathf.RoundToInt(Input.mousePosition.y);
    if (mouseX >= Screen.width)
    {
        if (mouseY >= Screen.height)
        {
            return MouseEdgeState.TopRight;
        }
        else if (mouseY <= 0)
        {
            return MouseEdgeState.DownRight;
        }
        else
        {
            return MouseEdgeState.Right;
        }
    }
    else if (mouseX <= 0)
    {
        if (mouseY >= Screen.height)
        {
            return MouseEdgeState.TopLeft;
        }
        else if (mouseY <= 0)
        {
            return MouseEdgeState.DownLeft;
        }
        else
        {
            return MouseEdgeState.Left;
        }
    }
    else
    {
        if (mouseY >= Screen.height)
        {
            return MouseEdgeState.Top;
        }
        else if (mouseY <= 0)
        {
            return MouseEdgeState.Down;
        }
        else
        {
            return MouseEdgeState.Unknown;
        }
    }
}

相關文章

Ted Liou

雲科碩士在讀中,專注於 Unity C#、TouchDesigner 技術,常把技術筆記分享到部落格,偶爾還直接挪用文章來當教材的研究生。