man standing on cliff

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

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

此腳本是使用傳統 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;
        }
    }
}

發表站內留言 取消回覆