Skip to content

Instantly share code, notes, and snippets.

@nicloay
Created May 4, 2020 10:29
Show Gist options
  • Save nicloay/7cea1c4422f480c0f3760ed66e1293ea to your computer and use it in GitHub Desktop.
Save nicloay/7cea1c4422f480c0f3760ed66e1293ea to your computer and use it in GitHub Desktop.
using UnityEngine;
using UnityEngine.EventSystems;
namespace SceneTransition.Demo
{
/// <summary>
/// Custom Input module:
/// If cursor is locked, send mouse events from center of the screen.
///
/// Found this hack here https://forum.unity.com/threads/fake-mouse-position-in-4-6-ui-answered.283748/#post-3600421
/// </summary>
public class InputModuleWithLockedCursor : StandaloneInputModule
{
protected override MouseState GetMousePointerEventData(int id)
{
var mouseState = base.GetMousePointerEventData(id);
if (Cursor.lockState == CursorLockMode.Locked)
{
var buttonData = mouseState.GetButtonState(0).eventData.buttonData;
buttonData.position = new Vector2(Screen.width / 2.0f, Screen.height / 2.0f);
buttonData.delta = Vector2.zero;
eventSystem.RaycastAll(buttonData, m_RaycastResultCache);
RaycastResult firstRayCast = FindFirstRaycast(m_RaycastResultCache);
buttonData.pointerCurrentRaycast = firstRayCast;
mouseState.SetButtonState(PointerEventData.InputButton.Left, StateForMouseButton(0), buttonData);
}
return mouseState;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment