Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Forked from Thaina/CursorLock.cs
Created November 8, 2024 12:24
Show Gist options
  • Select an option

  • Save unitycoder/66e83bc9adbaf697f71ce07cdee7b62b to your computer and use it in GitHub Desktop.

Select an option

Save unitycoder/66e83bc9adbaf697f71ce07cdee7b62b to your computer and use it in GitHub Desktop.

Revisions

  1. @Thaina Thaina created this gist Mar 26, 2023.
    57 changes: 57 additions & 0 deletions CursorLock.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    using System.Collections;
    using System.Collections.Generic;

    #if UNITY_EDITOR_WIN || UNITY_WEBGL
    using System.Runtime.InteropServices;
    #endif

    using UnityEngine;

    public static class CursorLock
    {
    public static bool ActualState => pointerLocked && Cursor.lockState != CursorLockMode.None;
    #if UNITY_EDITOR_WIN
    [StructLayout(LayoutKind.Sequential)]
    public struct RectStruct
    {
    public int Left;
    public int Top;
    public int Right;
    public int Bottom;

    public static implicit operator RectInt(RectStruct rect) => new RectInt(rect.Left,rect.Top,rect.Right - rect.Left,rect.Bottom - rect.Top);
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    public static extern bool GetClipCursor(out RectStruct lprect);

    static bool pointerLocked
    {
    get
    {
    var value = GetClipCursor(out var lprect);
    var rect = (RectInt)lprect;
    return value && rect.width <= Screen.width && rect.height <= Screen.height;
    }
    }

    #elif UNITY_WEBGL
    static bool pointerLocked;
    [AOT.MonoPInvokeCallback(typeof(System.Action<bool>))]
    static void OnPointerLockChanged(bool locked)
    {
    pointerLocked = locked;
    }

    [DllImport("__Internal")]
    private static extern void JS_RegisterLockCursorFunction(System.Action<bool> callback);

    [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
    static void PointerLockChangedRegister()
    {
    JS_RegisterLockCursorFunction(OnPointerLockChanged);
    }
    #else
    static bool pointerLocked => false;
    #endif
    }
    8 changes: 8 additions & 0 deletions CursorLock.jslib
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,8 @@
    mergeInto(LibraryManager.library,{
    JS_RegisterLockCursorFunction: function(onPointerLockChanged) {
    Module['dynCall_vi'](onPointerLockChanged,document.pointerLockElement == Module["canvas"]);
    document.addEventListener("pointerlockchange",function() {
    Module['dynCall_vi'](onPointerLockChanged,document.pointerLockElement == Module["canvas"]);
    });
    },
    });