using SepCore.InputModule; using UnityEngine; namespace SepCore.InputModule.Runtime.VirtualInput { [RequireComponent(typeof(Joystick))] public sealed class VirtualJoystickBridge : MonoBehaviour { [SerializeField] private InputActionId _actionId = InputActionId.Move; [SerializeField] private InputContextId _contextId = InputContextId.GameplayExplore; [SerializeField] private bool _injectDeviceKind = true; [SerializeField] private InputModuleComponent _inputModule; private Joystick _joystick; private Vector2 _previousDirection; private bool _wasPressed; private void Awake() { _joystick = GetComponent(); } private void Update() { Vector2 direction = _joystick.Direction; bool isPressed = direction.sqrMagnitude > 0f; if (!_wasPressed && isPressed) { Inject(InputCommandPhase.Started, direction); Inject(InputCommandPhase.Performed, direction); } else if (_wasPressed && isPressed) { if ((direction - _previousDirection).sqrMagnitude > 0.0001f) { Inject(InputCommandPhase.Performed, direction); } } else if (_wasPressed && !isPressed) { Inject(InputCommandPhase.Canceled, Vector2.zero); } if (isPressed && _injectDeviceKind) { TryForceDeviceKind(); } _previousDirection = direction; _wasPressed = isPressed; } private void Inject(InputCommandPhase phase, Vector2 direction) { InputModuleComponent inputModule = GetInputModule(); if (inputModule == null || !inputModule.IsInitialized) { return; } var command = new InputCommand( _actionId, _contextId, phase, InputDeviceKind.Touch, direction, direction.magnitude, Time.time); inputModule.InjectCommand(command); } private void TryForceDeviceKind() { InputModuleComponent inputModule = GetInputModule(); if (inputModule == null || !inputModule.IsInitialized) { return; } inputModule.ForceDeviceKind(InputDeviceKind.Touch); } private InputModuleComponent GetInputModule() { if (_inputModule != null) { return _inputModule; } _inputModule = FindObjectOfType(); return _inputModule; } } }