Skip to content

Instantly share code, notes, and snippets.

@Thaina
Created March 26, 2023 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Thaina/3b7d49340041dae390bc4ef3e4f2558b to your computer and use it in GitHub Desktop.
Save Thaina/3b7d49340041dae390bc4ef3e4f2558b to your computer and use it in GitHub Desktop.
Actual pointer lock value in unity webgl and windows editor
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
}
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"]);
});
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment