Files
SMD/Assets/Scripts/DesktopMachineControls.cs
T

252 lines
9.9 KiB
C#

using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.UI;
using UnityEngine.UI;
using UnityEngine.XR.Interaction.Toolkit;
using UnityEngine.XR.Interaction.Toolkit.Interactables;
using UnityEngine.XR.Interaction.Toolkit.Interactors;
using UnityEngine.XR.Interaction.Toolkit.UI;
[RequireComponent(typeof(EventSystem))]
public sealed class DesktopMachineControls : MonoBehaviour
{
private const float EyeHeight = 1.36f;
private const float Reach = 5f;
private const float HoldDistancePerScrollStep = 0.18f;
private readonly List<RaycastResult> uiHits = new();
private Camera playerCamera;
private CharacterController controller;
private XRRayInteractor mouseInteractor;
private XRInteractionManager interactionManager;
private EventSystem eventSystem;
private PointerEventData pointer;
private float yaw;
private float pitch;
private float fallSpeed;
private bool holding;
private MachineTaskPanel taskPanel;
private void Awake()
{
playerCamera = Camera.main;
interactionManager = FindAnyObjectByType<XRInteractionManager>();
if (playerCamera == null || interactionManager == null)
{
Debug.LogError("Desktop controls require a Main Camera and XR Interaction Manager.", this);
enabled = false;
return;
}
var player = new GameObject("Desktop Player") { layer = 2 };
player.transform.SetPositionAndRotation(playerCamera.transform.position - Vector3.up * EyeHeight, Quaternion.identity);
controller = player.AddComponent<CharacterController>();
controller.height = 1.5f;
controller.radius = 0.22f;
controller.center = Vector3.up * 0.75f;
controller.stepOffset = 0.18f;
controller.minMoveDistance = 0f;
playerCamera.transform.SetParent(player.transform, true);
yaw = playerCamera.transform.eulerAngles.y;
pitch = Mathf.DeltaAngle(0f, playerCamera.transform.eulerAngles.x);
eventSystem = GetComponent<EventSystem>();
pointer = new PointerEventData(eventSystem);
if (TryGetComponent<XRUIInputModule>(out var previousModule))
previousModule.enabled = false;
var ui = gameObject.AddComponent<InputSystemUIInputModule>();
ui.cursorLockBehavior = InputSystemUIInputModule.CursorLockBehavior.ScreenCenter;
foreach (var canvas in FindObjectsByType<Canvas>(FindObjectsInactive.Include))
{
if (canvas.renderMode == RenderMode.WorldSpace && canvas.worldCamera == null)
canvas.worldCamera = playerCamera;
if (canvas.TryGetComponent<TrackedDeviceGraphicRaycaster>(out var trackedRaycaster))
{
trackedRaycaster.enabled = false;
if (!canvas.TryGetComponent<GraphicRaycaster>(out _))
canvas.gameObject.AddComponent<GraphicRaycaster>();
}
}
var rayObject = new GameObject("Desktop Interaction Ray");
rayObject.SetActive(false);
rayObject.transform.SetParent(playerCamera.transform, false);
var attach = new GameObject("Held Item Anchor").transform;
attach.SetParent(rayObject.transform, false);
mouseInteractor = rayObject.AddComponent<XRRayInteractor>();
mouseInteractor.interactionManager = interactionManager;
mouseInteractor.referenceFrame = player.transform;
mouseInteractor.rayOriginTransform = rayObject.transform;
mouseInteractor.attachTransform = attach;
mouseInteractor.interactionLayers = -1;
mouseInteractor.enableUIInteraction = false;
mouseInteractor.useForceGrab = true;
mouseInteractor.manipulateAttachTransform = false;
mouseInteractor.maxRaycastDistance = Reach;
rayObject.SetActive(true);
taskPanel = gameObject.AddComponent<MachineTaskPanel>();
}
private void Start() => SetCursorLocked(true);
private void Update()
{
var mouse = Mouse.current;
var keyboard = Keyboard.current;
if (mouse == null || keyboard == null)
return;
if (keyboard.escapeKey.wasPressedThisFrame)
{
ReleaseItem();
SetCursorLocked(false);
return;
}
if (Cursor.lockState != CursorLockMode.Locked)
{
if (mouse.leftButton.wasPressedThisFrame)
SetCursorLocked(true);
return;
}
var mouseDelta = mouse.delta.ReadValue() * 0.12f;
yaw += mouseDelta.x;
pitch = Mathf.Clamp(pitch - mouseDelta.y, -85f, 85f);
playerCamera.transform.rotation = Quaternion.Euler(pitch, yaw, 0f);
MovePlayer(keyboard);
if (mouse.leftButton.wasPressedThisFrame)
TryPickUp();
if (!mouse.leftButton.isPressed)
ReleaseItem(snapTape: mouse.leftButton.wasReleasedThisFrame);
if (holding && mouseInteractor.hasSelection)
{
var attach = mouseInteractor.attachTransform;
var position = attach.localPosition;
var scroll = mouse.scroll.ReadValue().y;
if (Application.platform is RuntimePlatform.WindowsEditor or RuntimePlatform.WindowsPlayer &&
InputSystem.settings.scrollDeltaBehavior == InputSettings.ScrollDeltaBehavior.KeepPlatformSpecificInputRange)
scroll /= 120f;
position.z = Mathf.Clamp(position.z + scroll * HoldDistancePerScrollStep, 0.18f, Reach);
attach.localPosition = position;
float rotation = Axis(keyboard.eKey.isPressed, keyboard.qKey.isPressed);
attach.Rotate(Vector3.forward, rotation * 90f * Time.deltaTime, Space.Self);
}
}
private void TryPickUp()
{
var ray = playerCamera.ViewportPointToRay(new Vector3(0.5f, 0.5f));
var hits = Physics.RaycastAll(ray, Reach, Physics.DefaultRaycastLayers, QueryTriggerInteraction.Collide);
Array.Sort(hits, (first, second) => first.distance.CompareTo(second.distance));
foreach (var hit in hits)
{
if (interactionManager.TryGetInteractableForCollider(hit.collider, out var interactable) &&
interactable is IXRSelectInteractable target &&
interactionManager.IsSelectPossible(mouseInteractor, target))
{
if (HasUIInFront(hit.distance))
return;
bool isReel = target.transform.TryGetComponent<BabinaScript>(out _);
Quaternion holdRotation = playerCamera.transform.rotation;
if (isReel)
holdRotation *= Quaternion.Euler(0f, 90f, 0f);
mouseInteractor.attachTransform.SetPositionAndRotation(hit.point, holdRotation);
mouseInteractor.StartManualInteraction(target);
holding = mouseInteractor.IsSelecting(target);
if (holding && isReel)
taskPanel?.ReelPickedUp();
return;
}
if (!hit.collider.isTrigger)
return;
}
}
private bool HasUIInFront(float objectDistance)
{
pointer.position = playerCamera.pixelRect.center;
uiHits.Clear();
eventSystem.RaycastAll(pointer, uiHits);
foreach (var hit in uiHits)
{
if (hit.distance <= objectDistance + 0.02f &&
(ExecuteEvents.GetEventHandler<IPointerClickHandler>(hit.gameObject) != null ||
ExecuteEvents.GetEventHandler<IPointerDownHandler>(hit.gameObject) != null ||
ExecuteEvents.GetEventHandler<IDragHandler>(hit.gameObject) != null))
return true;
}
return false;
}
private void ReleaseItem(bool snapTape = false)
{
if (!holding)
return;
holding = false;
var released = mouseInteractor.firstInteractableSelected;
mouseInteractor.EndManualInteraction();
if (!snapTape || released == null || !released.transform.TryGetComponent<MaterialRopeDetachAction>(out _))
return;
foreach (var reel in FindObjectsByType<BabinaScript>())
{
if (reel.TrySnapTape(released))
break;
}
}
private void MovePlayer(Keyboard keyboard)
{
var selected = eventSystem.currentSelectedGameObject;
var typing = selected != null &&
((selected.TryGetComponent<TMPro.TMP_InputField>(out var tmpField) && tmpField.isFocused) ||
(selected.TryGetComponent<InputField>(out var inputField) && inputField.isFocused));
var input = typing ? Vector3.zero : new Vector3(
Axis(keyboard.dKey.isPressed, keyboard.aKey.isPressed), 0f,
Axis(keyboard.wKey.isPressed, keyboard.sKey.isPressed));
var direction = Quaternion.Euler(0f, yaw, 0f) * Vector3.ClampMagnitude(input, 1f);
var speed = keyboard.shiftKey.isPressed ? 3f : 1.4f;
fallSpeed = controller.isGrounded ? -2f : Mathf.Max(-20f, fallSpeed + Physics.gravity.y * Time.deltaTime);
controller.Move((direction * speed + Vector3.up * fallSpeed) * Time.deltaTime);
}
private void OnGUI()
{
if (Cursor.lockState == CursorLockMode.Locked && Event.current.type == EventType.Repaint)
GUI.DrawTexture(new Rect(Screen.width * 0.5f - 2f, Screen.height * 0.5f - 2f, 4f, 4f), Texture2D.whiteTexture);
}
private static float Axis(bool positive, bool negative) => (positive ? 1f : 0f) - (negative ? 1f : 0f);
private static void SetCursorLocked(bool locked)
{
Cursor.lockState = locked ? CursorLockMode.Locked : CursorLockMode.None;
Cursor.visible = !locked;
}
private void OnApplicationFocus(bool focused)
{
if (!focused)
{
ReleaseItem();
SetCursorLocked(false);
}
}
private void OnDisable()
{
ReleaseItem();
SetCursorLocked(false);
}
}